【发布时间】:2019-10-26 13:52:43
【问题描述】:
我们的风格定义如下:
<Style x:Key="StartButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Button ... Style="{StaticResource StartBtnStyle}">
<Button.Content>
<StackPanel>
<TextBlock x:Name="Line1" Text="..." FontSize="20" />
<TextBlock x:Name="Line2" Text="..." FontSize="8" />
</StackPanel>
</Button.Content>
</Button>
</ControlTemplate>
</Setter.Value>
</Setter>
我们动态创建一个按钮:
var button = new Button() {
Margin = new Thickness(3d,3d,3d,10d),
Style = FindResource("StartButtonStyle") as Style,
};
我们要在新按钮内找到“Line1”文本块,并设置Text属性:
var line1 = (TextBlock)button.FindName("Line1");
但它只找到“null”:(我们应该如何在按钮内找到文本块?任何建议都非常感谢!提前致谢!
【问题讨论】:
-
看看这个线程stackoverflow.com/questions/636383/…你应该检查UI元素树,
FindName返回null,因为它位于stackpanel内 -
你的意思是“FindName”不是递归函数?嗯:(这种特殊情况我可以给stackpanel命名,按名称找到它,然后在里面找到Line1?我应该试试......
标签: wpf templates dynamic properties