WPF:找不到触发器目标“ cc”。目标必须出现在任何设置器,触发器之前 [英] WPF: Can not find the Trigger target 'cc'. The target must appear before any Setters, Triggers
问题描述
以下代码有什么问题?
在编译过程中出现此错误:
I get this error during compilation:
属性 TargetName不代表 Setter的有效目标,因为未找到名为 cc的元素。确保在使用该目标的任何设置器,触发器或条件之前声明了该目标。
如何重构我的代码以便可以对其进行编译没有错误?
How do I have to refactor my code so I can compile it without error?
我只想切换数据模板,并将DataTrigger绑定到我的PersonViewModel中的值!
I just want to switch a datatemplate with DataTrigger bound to a value in my PersonViewModel!
<ContentControl x:Name="cc" Grid.Column="1">
<DataTemplate>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=CurrentPersonViewModel.IsNew}" Value="True">
<Setter TargetName="cc" Property="ContentTemplate" Value="{DynamicResource NewPersonId}" />
</DataTrigger>
<DataTrigger Binding="{Binding Path=CurrentPersonViewModel.IsNew}" Value="False">
<Setter TargetName="cc" Property="ContentTemplate" Value="{DynamicResource SelectedPersonId}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ContentControl>
推荐答案
更新
您可以为ContentControl使用样式并从此处更改ContentTemplate
You can use a Style for the ContentControl and change the ContentTemplate from there
<ContentControl Name="cc" Grid.Column="1">
<ContentControl.Style>
<Style TargetType="ContentControl">
<Setter Property="ContentTemplate" Value="{DynamicResource SelectedPersonId}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=CurrentPersonViewModel.IsNew}" Value="True">
<Setter Property="ContentTemplate" Value="{DynamicResource NewPersonId}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
更新
我不明白为什么DataTemplate中的View不会继承DataContext。通过使用它可以正常工作,但我看不到为什么这是必需的
UPDATE
I don't understand why the View's in the DataTemplate doesn't inherit the DataContext. Got it working by using this but I can't see why this is necessary
<DataTemplate x:Key="NewPersonId">
<local:NewPersonView DataContext="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContentControl}}, Path=DataContext.CurrentPersonViewModel}" />
</DataTemplate>
<DataTemplate x:Key="SelectedPersonId">
<local:SelectedPersonView DataContext="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContentControl}}, Path=DataContext.SelectedPersonViewModel}"/>
</DataTemplate>
这篇关于WPF:找不到触发器目标“ cc”。目标必须出现在任何设置器,触发器之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!