ashish saxena
ashish saxena

Reputation: 3

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?

Upvotes: 0

Views: 949

Answers (1)

Nitesh
Nitesh

Reputation: 7409

You can set BorderBrush of your Button and bind it with BorderBrush of Border control in ControlTemplate.

So when you will set BorderBrush for your Button from code behind it will reflect to underlying binding and so on your Border control in ControlTemplate.

<Page.Resources>
    <Style x:Key="MyButtonStyle" TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border x:Name="btnBorder"
                            BorderBrush="{TemplateBinding BorderBrush}" 
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Background="{TemplateBinding Background}">
                        <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center"/>                            
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Page.Resources>

This is how you can apply the Style

<StackPanel>

<Button Style={StaticResource MyButtonStyle} Name="btn1" Content="Test Button 1" 
        BorderBrush="Red"/>

<Button Style={StaticResource MyButtonStyle} Name="btn2" Content="Test Button 2" 
        BorderBrush="Green"/>

</StackPanel>

Upvotes: 1

Related Questions