如何将独特样式应用于XAML中没有代码隐藏的数据网格中的单个单元格

时间:2016-05-27 16:23:45

标签: c# wpf datagrid caliburn.micro

我在这里找到了这个解决方案Change DataGrid cell colour based on values,但是想把它降低到另一个级别,这样我可以有不同的条件来改变每个单元格的颜色,并假设最简单的方法是为每个单元应用不同的样式细胞

简而言之,在数据网格中访问单个单元格的XAML是什么?

更新:根据以下建议(@OmegaMan)发现: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"/> 

但我仍坚持如何修改以使其引用datagrid列和行类如下

    <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>

更新2 我刚刚发现这似乎更接近我的需要,但我不确定如何修改以使其特定于单个单元格。

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

1 个答案:

答案 0 :(得分:0)

在样式上使用数据触发器并绑定到可识别特定单元格的数据,在这种情况下标记名称为“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>

对于目标列,请指定样式

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

程序运行的时间看到它的运行情况:

enter image description here