WPF Datagrid - Column Binding related to other columns

六眼飞鱼酱① 提交于 2019-12-25 01:09:28

问题


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

state|Color1|Color2|Color3|...

I want to do this:

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?


回答1:


Multibinding is the way!

Here how I solved:

<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>

And the Converter:

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();
    }
}


来源:https://stackoverflow.com/questions/23545703/wpf-datagrid-column-binding-related-to-other-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!