views:

178

answers:

2

Hi !

Suppose we have a very 'XAML long' ControlTemplate for our Control. And we want to add just 1 Button to the Template. MSDN claims that 'There is no way to replace only part of the visual tree of a control'. Do I really have to copy all that ControlTemplate and add my Button to it?

Or: Is there any possibility how to provide some kind of an interface to a specific element? For example a TextBox, so that everyone could easily template it, without having to reapeat the whole ControlTemplate.

Thanks !

A: 

MSDN is correct. Gotta copy the entire ControlTemplate.

qntmfred
+2  A: 

As qntmfred has said, you can't do this directly. However, if you own the control that you want to customise (which it sounds like you do), then you can do this by adding suitable customisation properties, such as a CustomButtons property (which each user of the control could add their own buttons to) or an ExtensionContent property (which each user of the control could set to whatever content they wanted -- leave it empty, add a single control, or add a panel with as many things as they wanted on it). Your ControlTemplate would assign no semantics to these properties, but just host them as they were given to it. For example, suppose you provided an ExtensionContent property. Your ControlTemplate could present this using a ContentPresenter:

<ContentPresenter ContentSource="ExtensionContent" />

And your users could put whatever they wanted in it:

<s:StefansControl>
  <s:StefansControl.ExtensionContent>
    <StackPanel Orientation="Horizontal">
      <TextBlock Text="I'm custom content" />
      <Button Click="DoSomethingSurprising_Click">Click me</Button>
      <Image Source="something.jpg" />
    </StackPanel>
  </s:StefansControl.ExtensionContent>
</s:StefansControl>

Another possibly is to provide Style properties that you apply to parts of your control so that users can style them (including changing the template of that part (only) of the control) without replacing the entire style/template. This is kind of your "interface to a specific element" idea e.g. provide a FooBoxStyle property which gets applied to the "foo" TextBox.

In short, the idea is to build a certain measure of "partial replaceability" into the base template -- whether by using content, styles, templates or a combination of these. WPF doesn't provide a general notion of "partial replacement," but you can provide your own specific notion of partial replaceability provided you can predict what kind of partial replacements may be required.

itowlson