2
votes

I have a WPF ComboBox bound to a Collection List<Users>. I have applied a DataTemplate to show the FirstName using a TextBlock and this works as expected:

        <ComboBox Margin="5" ItemsSource="{Binding Path=TheUsers}" Name="cboUsers">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Margin="10" Text="{Binding Path=FirstName}">
                    </TextBlock>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>`

I have an item in my User class called IsActive which is a Boolean value. If true then I want to set the Foreground of the TextBlock to Navy.

I have spent so much time on what should be so easy and looked all over the web but most articles talk about changing the overall colour or binding to another element in the xaml.

I tried implementing a DataTrigger and after an hour removed the code because it was not working. It would not recognise my field name. Does anyone have a very simple guide to how to do this or what would be the best approach?

1

1 Answers

4
votes

As you apparently are not dealing with fields after all, this style should do what you want:

<TextBlock.Style>
    <Style TargetType="{x:Type TextBlock}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsActive}" Value="True">
                <Setter Property="Foreground" Value="Navy"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</TextBlock.Style>

It would not recognise my field name.

You cannot bind to fields, end of story.