WPF Datagrid-与其他列相关的列绑定 [英] WPF Datagrid - Column Binding related to other columns

查看:102
本文介绍了WPF Datagrid-与其他列相关的列绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有多个列的DataGrid。这些列中的某些内容类似于

I have a DataGrid with several Columns. Some of these columns are something like

state|Color1|Color2|Color3|...

我想这样做:

If state==1 => RowForeground = Color1
If state==2 => RowForeground = Color2
If state==3 => RowForeground = Color3
...

我可以想到的第一个解决方案是使用多个数据触发器:

The very first solution I can think is to use several Data Triggers:

<DataTrigger Binding="{Binding Path=state}" Value="0">
    <Setter Property="Foreground" Value="{Binding Path=color0, Converter={StaticResource str2clrConverter}}"/>                            
</DataTrigger>

<DataTrigger Binding="{Binding Path=state}" Value="1">
    <Setter Property="Foreground" Value="{Binding Path=color1, Converter={StaticResource str2clrConverter}}"/>                            
</DataTrigger>

<DataTrigger Binding="{Binding Path=state}" Value="2">
    <Setter Property="Foreground" Value="{Binding Path=color2, Converter={StaticResource str2clrConverter}}"/>                            
</DataTrigger>

[...]

是否有更好的解决方案?

Is there a better solution?

推荐答案

多绑定就是这样!

这是我的解决方法:

<Setter Property="Foreground">
    <Setter.Value>
        <MultiBinding Converter="{StaticResource frgConverter}">
            <Binding Path="state"/>

            <Binding Path="color1"/>
            <Binding Path="color2"/>
            <Binding Path="color3"/>
        </MultiBinding>
    </Setter.Value>
</Setter>

和转换器:

public class GridForegroundConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        int iColor;
        int nState = System.Convert.ToInt32(values[0]);

        if (nState < 0 || nState > 3)
            throw new ArgumentOutOfRangeException("State");

        iColor = System.Convert.ToInt32(values[nState + 1]);

        byte[] bytes = BitConverter.GetBytes(iColor);
        Color color = Color.FromRgb(bytes[2], bytes[1], bytes[0]);

        return new SolidColorBrush(color);
    }

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

这篇关于WPF Datagrid-与其他列相关的列绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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