Wpf 如何命名DataTriggeredUserControl以使其可见?
我在布局中有以下内容:Wpf 如何命名DataTriggeredUserControl以使其可见?,wpf,Wpf,我在布局中有以下内容: <ContentControl> <ContentControl.Style> <Style TargetType="{x:Type ContentControl}"> <Style.Triggers> <DataTrigger Binding="{Binding CurrentPane}" Value="Pane1"> <Setter Prope
<ContentControl>
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding CurrentPane}" Value="Pane1">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ContentControl}">
<uc:UserControl x:Name="?????" />
简单地说,UserControl
是基于DataTrigger
加载到模板中的。除了一件事之外,所有这些都工作得非常出色:无论我如何命名这个UserControl
,以便它出现在主布局中,它都不会出现。我需要获取控件的引用,以便将事件处理程序附加到它
如果有一个替代方案,即如何从主布局访问UserControl
,而不具体命名,那么这将是一个解决方案,也一样。您需要命名ContentControl
并从Template
属性获取ControlTemplate
,然后您可以使用其上的FindName
方法访问您的用户控件
:
<ContentControl Name="YourContentControl">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding CurrentPane}" Value="Pane1">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ContentControl}">
<uc:UserControl x:Name="YourUserControl" />
当然,如果在UserControl
尚未设置为模板时使用此代码,则会出现错误。因此,您应该检查null
:我是这样看的:定义Template
属性时要做的是定义类,以便在wpf对控件进行模板化时实例化。uc:UserControl
不是对实例的引用,因此不能使用x:Name
属性来引用它
如果您在单独的资源中定义了您的ControlTemplate
,那么可能更容易看出它不是一个实例:
<ControlTemplate x:Key="MyControlTemplate">
<uc:UserControl x:Name="MyUC">
</ControlTemplate>
<ContentControl x:Name="MyFirstContentControl">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding CurrentPane}" Value="Pane1">
<Setter Property="Template" Value="{StaticResource MyControlTemplate}">
[...]
<ContentControl x:Name="MySecondContentControl">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding CurrentPane}" Value="Pane1">
<Setter Property="Template" Value="{StaticResource MyControlTemplate}">
[...]
[...]
[...]
现在,如果你提到“MyUC”,它会提到两个实例中的哪一个?MyFirstContentControl
模板中的UserControl
,还是MySecondContentControl
中的模板?这就是为什么你必须动态地寻找类似(psoeudo代码)MyFirstControl.MyUC的东西,正如Sheridan解释的那样。为什么你不直接在xaml中设置EventHandler?如果你是说EventSetter,它们会在加载主页时使应用程序崩溃,我还无法找到原因。非常有希望,谢谢。是的,没错,我现在得到的是null
,但我会调查一下,然后再报告。
<ControlTemplate x:Key="MyControlTemplate">
<uc:UserControl x:Name="MyUC">
</ControlTemplate>
<ContentControl x:Name="MyFirstContentControl">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding CurrentPane}" Value="Pane1">
<Setter Property="Template" Value="{StaticResource MyControlTemplate}">
[...]
<ContentControl x:Name="MySecondContentControl">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding CurrentPane}" Value="Pane1">
<Setter Property="Template" Value="{StaticResource MyControlTemplate}">
[...]