简体   繁体   English

C# WPF 使用触发器将样式 Object 添加到 Datagrid 中的单元格

[英]C# WPF Add Style Object To Cells In Datagrid Using Trigger

Using the answer from this thread Programmatically add style trigger使用此线程的答案以编程方式添加样式触发器

Style st = new Style();

DataTrigger tg = new DataTrigger()
{
    Binding = new Binding("PackageTechnology_c"),
    Value = "Plastic"
};

tg.Setters.Add(new Setter()
{
    Property = Control.BackgroundProperty,
    Value = ColorConverter.ConvertFromString("Red")
});

st.Triggers.Add(tg);  

I want to be able to add styles and trigger to my Datagrid at run time.我希望能够在运行时添加 styles 并触发到我的 Datagrid。 Once I have created this style object, how to I add the style to my datagrid?一旦我创建了这种样式 object,如何将样式添加到我的数据网格中? I am not looking to do this in the XML, since I am dynamically creating styles are runtime.我不想在 XML 中执行此操作,因为我正在动态创建 styles 是运行时的。 How do I do this with code-behind?我如何使用代码隐藏来做到这一点?

I tried:我试过了:

datagrid.Style = st;

which results in this:结果是: 风格

If I do:如果我做:

datagrid.CellStyle = st;

then I get this:然后我得到这个: 在此处输入图像描述

But what I want is for the cell that has the value: "Plastic" inside the column "Package Technology" to turn red.但我想要的是具有值的单元格:“包装技术”列中的“塑料”变为红色。 Is there a way to achieve this?有没有办法做到这一点?

What you're looking for is DataGridColumn.CellStyle .您正在寻找的是DataGridColumn.CellStyle It will apply the given Style to all cells in that specific column, instead of every cell in the DataGrid .它将给定Style应用于该特定列中的所有单元格,而不是DataGrid中的每个单元格。

Since you're auto-generating your columns, you would make use of the DataGrid.AutoGeneratingColumn event.由于您正在自动生成列,因此您将使用DataGrid.AutoGeneratingColumn事件。 It gets raised for each auto-generated column when it gets created.它在创建时为每个自动生成的列引发。 You can use the argument to check which column is being created, and if it is the PackageTechnologyc column then you would create and set the Style .您可以使用该参数来检查正在创建哪个列,如果它是PackageTechnologyc列,那么您将创建并设置Style

If you were defining your columns in XAML, you would have <DataGrid Name="datagrid"... , and then somewhere later <DataGridTextColumn Header="PackageTechnologyc"... .如果您在 XAML 中定义列,您将有<DataGrid Name="datagrid"... ,然后在稍后的某个地方<DataGridTextColumn Header="PackageTechnologyc"... In that case you'd just add a Name to the DataGridTextColumn and then reference it like so: packageTechnologyColumn.Style = st;在这种情况下,您只需向DataGridTextColumn添加一个Name ,然后像这样引用它: packageTechnologyColumn.Style = st; . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM