问题描述:

I found this solution here Change DataGrid cell colour based on values but want to take it down another level so that I can have different conditions for changing the color for each cell and assume the most straightforward way would be to apply different styles to each single cell.

In short, what is the XAML to access a singular cell in a datagrid?

UPDATE: At suggestion below (@OmegaMan) found this: How can I use Grid.Row Property as a DataBinding Path for a MultiDataTrigger Condition?

<Condition Binding="{Binding RelativeSource={RelativeSource Self}, Path= (Grid.Row)}" Value="2"/>

but am stuck on how to modify to make it refer to a datagrid column and row kind of like below

 <Style x:Key="colorDataGridCellStyle" TargetType="{x:Type DataGridCell}">

<Setter Property="Background" Value="AntiqueWhite" />

<Style.Triggers>

<MultiDataTrigger>

<MultiDataTrigger.Conditions>

<Condition Property ="Column"

Value="2"/>

<Condition Property ="Row"

Value="2"/>

<Condition {the value of this particular cell (2,2) is between two values, thinking this will mostly have to be in the viewModel but maybe can have more here} />

</MultiDataTrigger.Conditions>

<Setter Property="Foreground" Value="Green" />

</MultiDataTrigger>

</Style.Triggers>

</Style>

UPDATE 2

I just found this which seems closer to what I need but I'm not sure how to modify to allow for making it specific to single cells.

How do I change a datagrid row color in XAML based on the value listed in code?

网友答案:

Use a datatrigger on a style and bind to data which can identify a specific cell, in this case flag anyone whose name is "Johnson":

<Style x:Key="colorDataGridCellStyle" TargetType="{x:Type DataGridCell}">
    <Setter Property="Background" Value="AntiqueWhite" />
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=Last}" Value="Johnson">
            <Setter Property="Foreground" Value="Blue" />
        </DataTrigger>
    </Style.Triggers>
</Style>

For the target column specify the style

<DataGridTextColumn Header="The Name"
                    Binding="{Binding Last}"
                    CellStyle="{StaticResource colorDataGridCellStyle}"/>

The when the program runs see it in action:

相关阅读:
Top