本文介绍了WPF DataTrigger“找不到触发目标"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过其他类似标题的问题,我认为这是一个不同的问题.

I've read other questions with similar titles and I think this is a different question.

我有一个数据绑定组合框.每个项目都有一个状态"和一个名称",显示文本是通过使用 TextBlock 和 2 个 Run 将两者串联起来的.如果它是NotComplete",我想用红色突出显示状态"部分.这是我的 XAML:

I have a data-bound combobox. Each item has a "status" and a "name" and the display text is a concatenation of both by using a TextBlock with 2 Run's . I want to highlight the "status" part in red if it's "NotComplete". Here is my XAML:

<ComboBox ItemsSource="{Binding Results}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding Status}" Value="NotComplete">
                    <Setter TargetName="txtStatus" Property="Foreground" Value="Red" />
                </DataTrigger>
            </DataTemplate.Triggers>
            <TextBlock>
                <Run Text="{Binding Status}" Name="txtStatus"/>
                <Run Text="{Binding Name" />
            </TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

我收到一个构建错误说

找不到触发器目标txtStatus".

我尝试了其他一些东西(例如使用 x:Name 而不是 Name),但得到了同样的错误.我在正确的方向上吗?我该如何解决这个问题?

I tried a few other things (such as using x:Name rather than Name) but got the same error. Am I on the right direction? How can I fix this?

推荐答案

必须首先声明触发器目标.更改顺序即可.

The trigger target has to be declared first. Change the order and it will work.

<DataTemplate>
    <TextBlock>
        <Run Text="{Binding Status}" Name="txtStatus" />
        <Run Text="{Binding Name}" />
    </TextBlock>
    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding Status}" Value="NotComplete">
            <Setter TargetName="txtStatus" Property="Foreground" Value="Red" />
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>

这篇关于WPF DataTrigger“找不到触发目标"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 00:52