c# - 来自 XAML 中不同属性的 WPF DataGrid 单元格样式

标签 c# wpf xaml

是否可以将数据网格列值绑定(bind)到 ItemsSource 中指定的绑定(bind)类的一个属性,但引用该类中的另一个属性来设置单元格样式?

这是一个代码示例:

<DataGrid ItemsSource="MyCollection">
  <DataGridTextColumn Header="MyColumn" Binding={Binding ColumnText} />
  <DataGridTextColumn Header="MyColumn2" Binding={Binding ColumnText2} />
</DataGrid>

假设我在 MyCollection 中的对象中还有两个属性(Enum 或 Brush),我想引用它们来设置各个单元格的背景颜色;这可以做到吗?

编辑 - 我需要对多个列执行此操作,每个列查看不同的属性以确定它应该是的颜色;我在上面的代码示例中添加了第二列。

我知道我可以根据 ColumnText 中的值设置样式,但这不是我需要做的。

我尝试设置样式数据触发器,但是当我尝试绑定(bind)时,我只能绑定(bind)到整个数据上下文中的某些内容,而不能绑定(bind)到填充当前行的对象中的另一个属性。

非常感谢!

最佳答案

如果我理解正确,您正在尝试通过行模型中的属性设置单元格背景。

您可以通过设置单元格样式来实现此目的,并将DataTrigger设置为该样式以绑定(bind)到您想要的属性。


示例

您想要将每个包含数字 3 的单元格涂成绿色:

<DataGrid ItemsSource="{Binding Rows}" AutoGenerateColumns="True">
    <DataGrid.CellStyle>
        <Style TargetType="{x:Type DataGridCell}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Number}" Value="3">
                    <Setter Property="Background">
                        <Setter.Value>
                            <SolidColorBrush Color="Green"/>
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.CellStyle>
</DataGrid>

当然,您可以使用您自己的属性以及您感兴趣的值来更改 Number 属性。

如果您想做一些更复杂的事情,例如值范围等,您应该使用传统的转换器方式。


编辑

如果你想为每列设置不同的单元格样式,你应该显式设置列:

<DataGrid ItemsSource="{Binding Rows}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Number}">
            <DataGridTextColumn.CellStyle>
                <Style TargetType="{x:Type DataGridCell}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Number}" Value="3">
                            <Setter Property="Background">
                                <Setter.Value>
                                    <SolidColorBrush Color="Green"/>
                                </Setter.Value>
                            </Setter>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </DataGridTextColumn.CellStyle>
        </DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

有一件重要的事情需要注意,

必须设置AutoGenerateColumns="False",否则列将生成两次。

关于c# - 来自 XAML 中不同属性的 WPF DataGrid 单元格样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36485313/

相关文章:

c# - 如何在使用 XAML 获取图像资源后释放/缓存图像资源

c# - 在 setter 中更改 SelectedItem 值对 ComboBox 没有影响

c# - 使用LINQ根据Where过滤List中的某个值

wpf - WPF 工具栏如何更改其按钮的样式?

c# - 使用 Newtonsoft C# 读取 Json 字符串

wpf - Datagrid将wpf c#绑定(bind)到datatable.defaultview : Last column of data missing but header is there

wpf - 相对于程序集的本地文件的 URI

c# - Tha xaml 图形在页面中有多个位置时消失

c# - 将具有多个参数的 F# 函数转换为 Func 类型 - MathNet.Numerics

c# - Microsoft ml.net 连接 2 列作为标签