开发者

WPF: How to highlight all the cells of a DataGrid meeting a condition?

开发者 https://www.devze.com 2022-12-12 11:52 出处:网络
The (wpftoolkit) datagrid generally represents a collection of objects with rows representing each object, and the columns the repective properties.

The (wpftoolkit) datagrid generally represents a collection of objects with rows representing each object, and the columns the repective properties.

I am not using it this way. I am using it to represent the "intersection" between 2 collections. Rows represent objects of collection A and columns represent objects in collections B. A cell at x,y represent some value from fn(collectionA[x],collectionB[y])开发者_如何转开发.

This works fine. Now I want to be able to query the cell values. I want the user to be able to do things like highlight all cells with value greater than 0? How do I do this with the datagrid?


One way is to create a data cell template that behaves in a corresponding manner (via controltemplates.triggers collection).

Another way is to create a data cell style and use style triggers to set the background when a given binding has a certain value (via style.triggers collection).

Or you can use a hybrid approach.

Inside your data cell template, you might have a border element containing everything. You can, for example, create an inline style for that border element.

<Border Width="Auto" Height="Auto" Padding="6,10,6,10" CornerRadius="0,0,20,20">
    <Border.Style>
        <Style TargetType="{x:Type Border}" >
            <Setter Property="Background" Value="White" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding Highlighted}" Value="True">
                    <Setter Property="Background" Value="{StaticResource GreenGradientSuccessBrush}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>    
    </Border.Style>
</Border>

If this is sitting in a data template, the datacontext of the border element will be the contained object, and the border trigger will fire when "Highlighted" property of the content (assuming content is a class with a "Highlighted" boolean property) is "True".

If your content is an integer and you want the trigger to fire when it is greater than zero you will have to use

<DataTrigger Binding="{Binding, Converter={StaticResource GreaterThanZeroConverter}}" Value="True">

where the GreaterThanZeroConverter is a suitable value converter.

0

精彩评论

暂无评论...
验证码 换一张
取 消