【发布时间】:2013-08-08 03:27:39
【问题描述】:
我想从后面的代码中获取控件模板中的元素。
在下面的 XAML 中,我想获取 Border 元素“btnBorder”,并将颜色从红色更改为 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>
我尝试过各种方法,例如
GetTemplateChild("btnBorder") object o = template.FindName("btnBorder", this.btn);
但这些方法返回 null。
请让我知道我在哪里做错了,或者从后面的代码访问模板子项的正确方法是什么?
【问题讨论】:
标签: c# .net wpf silverlight