我如何有条件地格式化datagrid [英] How do I conditionally format datagrid

查看:54
本文介绍了我如何有条件地格式化datagrid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是WPF的新手。我有一个包含15列数据的数据网格。其中一些是口粮,我想显示绿色字体颜色的比率小于1的那个和红色的大于1的那个。

有没有教程?



干杯



我尝试过:



我试图搜索,我发现Developer Express可以做到这一点

I am new to WPF. I have a datagrid with a 15 columns of data. some of them are rations and i want to show the one with ratio less than 1 in green color font colour and the ones greater than 1 in Red.
is there any tutorials?

Cheers

What I have tried:

I tried to search and i found that the Developer Express can do that

推荐答案

只需在Xaml中使用样式。请参阅下面的Xaml代码和数据网格所需的样式列。

Hi, just use style in Xaml. Refer below Xaml code, and style required columns of your datagrid.
<DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding YourProperty}" ClipboardContentBinding="{x:Null}" Header="Amount">
                    <DataGridTextColumn.CellStyle>
                        <Style TargetType="{x:Type DataGridCell}">
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding YourProperty, Converter={StaticResource NumberToBoolConverter}, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Value="True">
                                    <Setter Property="Background" Value="Green" />
                                    <Setter Property="Foreground" Value="White" />
                                </DataTrigger>

                                <DataTrigger Binding="{Binding YourProperty, Converter={StaticResource NumberToBoolConverter}, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Value="False">
                                    <Setter Property="Background" Value="Red" />
                                    <Setter Property="Foreground" Value="White" />
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </DataGridTextColumn.CellStyle>
                </DataGridTextColumn>
            </DataGrid.Columns>



使用此转换器,


Use this converter,

public class NumberToBooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        try
        {
            bool ToReturn = false;
            int ActualValue = System.Convert.ToInt32(value);

            if (ActualValue <= 1)
            {
                ToReturn = true;
            }
            else if (ActualValue > 1)
            {
                ToReturn = false;
            }

            return ToReturn;
        }
        catch
        {
            return false;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new InvalidOperationException("NumberToBooleanConverter can only be used OneWay.");
    }
}


这篇关于我如何有条件地格式化datagrid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆