0

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?

4

1 回答 1

1

您可以在 ControlTemplate中设置BorderBrush您的控件Button并将其与控件绑定。BorderBrushBorder

因此,当您BorderBrush为您的Buttonfrom 代码设置后面的代码时,它将反映到底层绑定等您BorderControlTemplate.

<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>

这是您可以应用的方法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>
于 2013-08-08T03:49:55.430 回答