Wednesday 7 August 2013

How to get the element in the control template in Silverlight?

How to get the element in the control template in Silverlight?

I want to get the element in the control template from code behind.
In the XAML below I want to get the Border element "btnBorder" and change
the color from red to any other color from code behind.
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel
Name ="st"
Margin="0,3,0,3"
Grid.Row="4"
Orientation="Horizontal">
<Button Name="btn" Height="22" Margin="0,0,25,0">
<Button.Template x:Uid="dd">
<ControlTemplate x:Name="tmp" TargetType="Button">
<Border x:Name="btnBorder" Background="Red">
<ContentPresenter VerticalAlignment="Center"
HorizontalAlignment="Center" />
</Border>
</ControlTemplate>
</Button.Template>
Test Button
</Button>
</StackPanel>
</Grid>
</Window>
I have tried various methods like
GetTemplateChild("btnBorder") object o = template.FindName("btnBorder",
this.btn);
but these methods are returning null.
Please let me know where I am doing wrong or what is the correct way to
access the template child from code behind?

No comments:

Post a Comment