Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361812

WPF/Silverlight : Templating Custom Control PARTIALLY

.

Hello guys,

Can we write our custom controls in such a way that later on we can re-template it partially? Means, without replacing the entire ControlTemplate, we want to change/override some of it's look and feel?

One way, of course, is this : copy the ControlTemplate code from generic.xaml, modify it's look and feel partially, and use it in your xaml, as shown below:

<MyCustomControl>
       <MyCustomControl.Template>
              <ControlTemplate>

                    <!-- paste the copied and modified code from generic.xaml here-->

              </ControlTemplate>
        </MyCustomControl.Template>

        <!--other code-->

</MyCustomControl>

But the problem with this approach is that, we make our xaml too verbose. And I seriously don't like it. I'm looking for some solution that may save me from polluting the xaml where I'm using my custom control.

Thanks in anticipation!

.

Upvotes: 6

Views: 250

Answers (3)

jpierson
jpierson

Reputation: 17384

I agree with most of what Martin says about ControlTemplates being pretty much an all or nothing thing in WPF and I was pretty frustrated myself when I came to this conclusion.

If your writing your own custom control however you can make it more flexible why composing or offering the ability to template pices of the control. For an example you can look at the newer WPF DataGrid control which has the ability to template different pieces of the control. Other headered content controls often have a separate template for the content and the header portion of the control making it possible to replace one but not the other.

Upvotes: 1

Kiang Teng
Kiang Teng

Reputation: 1705

I'm also facing the same problem where making one small edit requires me copying and pasting the entire default control template.

You can however define multiple resource dictionaries and use <ResourceDictionary.MergedDictionaries> to separate your markup from the control templates.

Your xaml markup will be much cleaner and look something like this:

 <Style>
        <Setter Property="Template" Value="{StaticResource SomeRandomTemplate}" />
 </Style>

Upvotes: 1

Martin Liversage
Martin Liversage

Reputation: 106956

Unfortunately modifying a control template is an all or nothing proposition. As you point out your XAML becomes very verbose when you modify a complex control template.

One approach (which is quite obvious anyway) is to build your UI from small composable parts hopefully making the control templates easier to work with.

You have the possibility of reusing styles by using the Style.BasedOn Property. Unfortunately, this doesn't solve your problem.

Upvotes: 1

Related Questions