Conditional Formatting of WPF DataGrid Cell Depend

2019-05-22 03:55发布

I have a user control that inherits from the WPF DataGrid control and to which I pass different List of objects and, so, the columns of the grid depend (i.e. are automatically generated) on the class of object that I send through.

<userc:cfDataGrid x:Name="grdResults" 
    FontStyle="Normal" 
    FontFamily="Microsoft Sans Serif" 
    FontSize="14" 
    RowHeight="30"  

    AutoGenerateColumns="True" 
    Margin="12" 
    AlternatingRowBackground="Gainsboro"  
    AlternationCount="2" 

    ItemsSource="{Binding Results}" 
    IsReadOnly="True" 
    HeaderNames="{Binding Headers}" >
</userc:cfDataGrid> 

Now, I'd like to also pass through a list of objects that have an attribute of SolidColorBrush data type and be able to use this value to set the background colour of the cell rather than display the actual value.

I have not done much work with styles etc and so I wanted to ask if anyone could give me some pointers on how to trap a column with a SolidColorBrush datatype - and perform the action described above - without depending on the name of the column?

Any pointers would be greatly appreciated!

CC

1条回答
\"骚年 ilove
2楼-- · 2019-05-22 04:47

I would use a DataTrigger that used a Converter to check if the object was a SolidColorBrush, and if so set the background color

Something like this:

<DataGrid.Resources>
    <Style TargetType="{x:Type DataGridCell}">
        <Style.Triggers>
            <!-- DataContext will be object for entire data row -->
            <DataTrigger Binding="{Binding MyBrushColorProperty, Converter={StaticResource IsSolidBrushColor}}" Value="True">
                <Setter Property="Background" Value="{Binding MyBrushColorProperty}" />
                <Setter Property="Content" Value="" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</DataGrid.Resources>
查看更多
登录 后发表回答