Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataTrigger "cannot find trigger target"

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

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>

I got a build error saying

Cannot find the Trigger target 'txtStatus'.

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?

like image 365
NS.X. Avatar asked Dec 16 '22 22:12

NS.X.


1 Answers

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>
like image 76
LPL Avatar answered Jan 14 '23 04:01

LPL