gpt4 book ai didi

c# - 基于列名及其在 WPF 中的值的 DataTriggers

转载 作者:行者123 更新时间:2023-11-30 21:48:11 25 4
gpt4 key购买 nike

我有一个 DataGrid,它在代码中使用 DataTable 自动生成其列。如果 X 列的值为 FALSE 或其他值,我需要更改行的背景颜色。我可以使用 AutoGeneratingColumn="OnAutoGeneratingColumn" 事件参数来实现吗?如果不是,我如何使用访问列值的 DataTriggers 更改行的样式并影响行的背景颜色?

编辑 1:直截了当的问题:如何根据某列的值更改行的背景颜色?

编辑 2:基于生成列事件,我可以这样做:

编辑 3:编码

public static void OnAutoGeneratingColumn(object sender, System.Windows.Controls.DataGridAutoGeneratingColumnEventArgs e)
{
try {

if (e.PropertyType == typeof(System.DateTime) && e.Column.Header.ToString() != "Data de Registo")
(e.Column as System.Windows.Controls.DataGridTextColumn).Binding.StringFormat = "dd/MM/yyyy";

if (e.PropertyType == typeof(System.DateTime) && e.Column.Header.ToString() == "Data de Registo")
(e.Column as System.Windows.Controls.DataGridTextColumn).Binding.StringFormat = "dd/MM/yyyy HH:mm:ss";
if (e.Column.Header.ToString() == "FT")
{
StringReader stringReader = new StringReader("<Style xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\""
+ " TargetType=\"{x:Type DataGridCell}\">"
+ " <Setter Property=\"Background\" Value=\"Red\"/>"
+ " </Style>");
XmlReader xmlReader = XmlReader.Create(stringReader);
Style style = (Style)System.Windows.Markup.XamlReader.Load(xmlReader);
e.Column.CellStyle = style;
}
}
catch (Exception) { }
}

所以我更改了列(它的单元格)的背景颜色,但我想要的是检查每一行的值,如果值为 X 则将其设置为红色,如果值为 Y 则设置为绿色。

最佳答案

DataGrid 使用 StyleDataTrigger。然后根据绑定(bind)的数据项进行格式化。

<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=<!--Your property name here-->}"
Value="False">
<Setter Property="Background" Value="<!-- Your desired Brush here-->" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>

如果要访问绑定(bind)数据项的默认索引器属性,请将路径设为 Path=[IndexerName]Path=[(sys:Int32)0].

关于c# - 基于列名及其在 WPF 中的值的 DataTriggers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37853601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com