如何在模板中使用控件?
问题描述:
<Style x:Key="abc" TargetType="{x:Type Window}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Window}">
<button x:name="btn">my button!!</button>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
...
<Window ... Style="{StaticResource styleMainWindow}">
我如何使用btn
按钮?
达到您的期望,
MessageBox.Show(this.btn1.name);
在编译时发生错误.并且 btn1 也没有出现在智能感知中.
was occured an error at compile time. and also btn1 didn't show up in intelisense.
答
尝试 FindName 方法.
假设this是您控件的上下文:
Assuming this is your Control's context:
var button = (Button)this.Template.FindName("btn", this);