Chepene
Chepene

Reputation: 1128

Modify Template in code-behind

In our app we use 3rd party library components. I need to change only one value in whole template. How can I archieve this without redefine template?

For example, controlTemplate:

<ControlTemplate TargetType="{x:Type Label}">
        <Border x:Name="PART_MainBorder"
                BorderBrush="Black" 
                BorderThickness="{TemplateBinding BorderThickness}">
            <ContentPresenter/>
        </Border>            
</ControlTemplate>

I need to change PART_MainBorder.BorderBrush. How can I do this?

I have found this link, but I can't believe there is no other way to do it..

Thanks.

Upvotes: 0

Views: 5504

Answers (1)

dkozl
dkozl

Reputation: 33364

I'm sure there are more elegant ways to do it in XAML but to answer your question template is nothing more but a cookie cuter so you cannot just start changing properties of template objects in code behind. You can modify template controls properties via control to which the template has been applied. In case of ControlTemlate it will be templated control and for DataTemplate it will be ContentPresenter used to generate content. So let's say that you have 2 Labels to which you applied template above:

<Label Content="A" x:Name="Label1"/>
<Label Content="B" x:Name="Label2"/>

an then in the code you can change Border.BorderBrush like this:

(Label1.Template.FindName("PART_MainBorder", Label1) as Border).BorderBrush = new SolidColorBrush(Colors.Red);
(Label2.Template.FindName("PART_MainBorder", Label2) as Border).BorderBrush = new SolidColorBrush(Colors.Orange);

worth noting that 2 Labels will have different BorderBrush color

Upvotes: 3

Related Questions