非常基本的场景,但我找不到解决方案,我有一个包含 ContentView 的页面,并且该 ContentView 的 ControlTemplate 属性根据使用 DataTrigger 的属性更改事件进行更改。这是代码:
<ContentPage.Resources>
<ControlTemplate x:Key="view1">
<Label x:Name="label1"/>
</ControlTemplate>
<ControlTemplate x:Key="view2">
<Label x:Name="label2"/>
</ControlTemplate>
</ContentPage.Resources>
<ContentView>
<ContentView.Triggers>
<DataTrigger TargetType="ContentView" Binding="{Binding MyCondition}" Value="True">
<Setter Property="ControlTemplate" Value="{StaticResource view1}"/>
</DataTrigger>
<DataTrigger TargetType="ContentView" Binding="{Binding MyCondition}" Value="False">
<Setter Property="ControlTemplate" Value="{StaticResource view2}"/>
</DataTrigger>
</ContentView.Triggers>
</ContentView>
-> 如何从页面访问“label1”和“label2”?我尝试使用 GetTemplateChild 方法但没有成功。感谢您对此的意见。
编辑:我确实尝试在 OnApplyTemplate 上使用 GetTemplateChild,但 OnApplyTemplate 从未被调用。不过,页面的 UI 已正确更新。
只能在调用
GetTemplateChild
方法后调用 OnApplyTemplate
方法。这是通过从模板化页面的 OnApplyTemplate 覆盖调用 GetTemplateChild 方法来实现的:
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
theFirstLabel = (Label)GetTemplateChild("label1");
theSecondLabel = (Label)GetTemplateChild("label2");
}
更多详情可以参考 从模板获取命名元素。