Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the font color in a cell of a WPF ListView depending on the value of the cell?

Tags:

c#

listview

wpf

<ListView ItemsSource="{Binding}" Name="myView">
            <ListView.View>
                <GridView>
                    <GridViewColumn DisplayMemberBinding="{Binding fieldA}" Header="Field A" />
                    <GridViewColumn DisplayMemberBinding="{Binding fieldB}" Header="Field B" />                    </GridView>
            </ListView.View>
        </ListView>

I would like to know how to format my list view so that if object.fieldA == "apples", the font is red in the fieldA cell.

Thanks boffins.

like image 255
jsj Avatar asked Apr 28 '12 12:04

jsj


1 Answers

You need to use a DataTemplate to show the fieldA value and add a trigger changing the Foreground property for a given value.

See also Data Templating Overview on MSDN.

<GridViewColumn Header="Field A">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <TextBlock x:Name="Txt" Text="{Binding fieldA}" />
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding fieldA}" Value="apples">
                    <Setter TargetName="Txt" Property="Foreground" Value="Red" />
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>
like image 119
Julien Lebosquain Avatar answered Oct 16 '22 17:10

Julien Lebosquain