C# Silverlight Datagrid:根据值更改单元格样式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/377030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 01:11:35  来源:igfitidea点击:

Silverlight Datagrid: Changing cell styles, based on values

c#silverlightdatagridcells

提问by Mindaugas Mozūras

I have some data. I want to go through that data and change cells (for example - Background color), if that data meets a certain condition. Somehow, I've not been able to figure it out how to do this seemingly easy thing in Silverlight.

我有一些数据。如果该数据满足特定条件,我想查看该数据并更改单元格(例如 - 背景颜色)。不知何故,我一直无法弄清楚如何在 Silverlight 中做这件看似简单的事情。

采纳答案by Simon Steele

This is slightly old code (from before RTM), but does something like what you're looking for. It checks some data on an object in a row and then sets the colour of the row accordingly.

这是稍微旧的代码(来自 RTM 之前),但执行的操作类似于您正在寻找的内容。它检查一行中某个对象的一些数据,然后相应地设置该行的颜色。

XAML:

XAML:

<my:DataGrid x:Name="Grid" Grid.Row="1" Margin="5" GridlinesVisibility="None" PreparingRow="Grid_PreparingRow">
    <my:DataGrid.Columns>
        <my:DataGridTextBoxColumn 
            DisplayMemberBinding="{Binding Cheese}" 
            Header="Cheese"></my:DataGridTextBoxColumn>
        <my:DataGridTextBoxColumn 
            DisplayMemberBinding="{Binding Biscuit}" 
            Header="Biscuit"></my:DataGridTextBoxColumn>
    </my:DataGrid.Columns>
</my:DataGrid>

Code:

代码:

this.Grid.AlternatingRowBackground = null; 

private void Grid_PreparingRow(object sender, DataGridRowEventArgs e)
{
    CheesyClass c = e.Row.DataContext as CheesyClass;
    if (c != null && c.Cheese == "cheddar")
    {
       e.Row.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 255, 125, 125));
    }
}

回答by Simon Steele

Actually this won't work in all examples. See these links for the 'proper' way of achieving this

实际上,这不适用于所有示例。有关实现此目的的“正确”方法,请参阅这些链接

http://silverlight.net/forums/p/27465/93474.aspx#93474

http://silverlight.net/forums/p/27465/93474.aspx#93474

http://silverlight.net/forums/t/27467.aspx

http://silverlight.net/forums/t/27467.aspx

回答by Rammesses

I've generally written custom ValueConverters for each data type being bound that return Visibility, Colour, etc.

我通常为每个绑定的数据类型编写自定义 ValueConverters,返回可见性、颜色等。

This gives a single point where the customisation rules are defined and I've found works very well.

这给出了定义自定义规则的一个点,我发现它非常有效。

Robin's second link describes writing a custom ValueConverter.

Robin 的第二个链接描述了编写自定义 ValueConverter。