我有一个包含多个列的DataGrid。其中一些列类似于
state|Color1|Color2|Color3|...
我想这样做:
If state==1 => RowForeground = Color1
If state==2 => RowForeground = Color2
If state==3 => RowForeground = Color3
...
我能想到的第一个解决方案是使用多个数据触发器:
<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>
[...]
有更好的解决方案吗?
答案 0 :(得分:1)
Multibinding就是这样!
我在这里解决了:
<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();
}
}