gridcontrol如何根据值来动态设置某一行的颜色

应用场景:当我们使用devexpress gridcontrol wpf控件时。可要会要根据这一行要显示的值来设置相应的颜色

可以通过下面方法来实现

一、先定义一个style

<local:Conv x:Key="c"/>

            <Style x:Key="optimizedRowStyle" TargetType="{x:Type dxg:RowControl}">                     

                        <Setter Property="Background" Value="{Binding Row.Column2, Converter={StaticResource c}}"/>
            </Style>

x:Type dxg:RowControl 说明这个style是针对行的

Binding Row.Column2 表示改背景颜色会根据第二列的值来动态设置其颜色

二、把style应用到控件上

        <dxg:GridControl ItemsSource="{StaticResource Data}" VerticalAlignment="Stretch" Height="400">
            <dxg:GridControl.Columns>
                <dxg:GridColumn FieldName="Column1"></dxg:GridColumn>
                <dxg:GridColumn FieldName="Column2"></dxg:GridColumn>
            </dxg:GridControl.Columns>
            <dxg:GridControl.View>
                <dxg:TableView AutoWidth="True" AllowEditing="False" RowStyle="{StaticResource optimizedRowStyle}" NavigationStyle="Row">
                </dxg:TableView>
            </dxg:GridControl.View>
        </dxg:GridControl>

是通过RowStyle依赖属性来设置

三、效果如下:

会根据第二列的值来显示不同的背景颜色

ps 下面把后台convert类贴出来大家看看

    public class Conv : IValueConverter {

        public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            if (!(value is int)) return new SolidColorBrush(Colors.White);
            if ((int)value % 3 == 0) return new SolidColorBrush(Colors.Red);
            return new SolidColorBrush(Colors.White);
        }

        public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            throw new System.NotImplementedException();
        }
    }

这个value就是column2列里面的值。

原文地址:https://www.cnblogs.com/tianmochou/p/6186128.html