将背景单元格颜色绑定到byte []类属性

时间:2016-10-13 15:17:56

标签: c# wpf binding multibinding

我阅读了很多关于我的问题的帖子,似乎多重绑定是最好的解决方案,但我无法使其发挥作用。

我需要将一个类属性(一个表示aRGB颜色的字节数组)绑定到背景数据网格颜色。

这是我的班级:

public class LedVals
{   ....
    public byte[] ColorT0 { get; set; } = new byte[4] { 0xFF, 0xFF, 0x00, 0x00 };
    ....
}

为此,我使用自定义样式:

    <Style TargetType="DataGridCell" x:Key="ColorPickerColorT0" 
       BasedOn="{StaticResource CommonCell}">
        <Setter Property="Background">
            <Setter.Value>
                <MultiBinding Converter="{StaticResource RgbConverter}">
                    <Binding Path="ColorT0" />
                </MultiBinding>
            </Setter.Value>
        </Setter>
        <Setter Property="Foreground" Value="Transparent"/>
        <Setter Property="Width" Value="35"></Setter>
    </Style>

对于颜色列受此影响:

    private void DgLedTable_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        if (e.PropertyName == "ColorT0")
        {
            e.Column.CellStyle = (sender as DataGrid).FindResource("ColorPickerColorT0") as Style;

        }
    }

我想我错过了Multibinding ......

感谢您的帮助。

编辑:

这要归功于Philip W Advice。

以下是转换器的修改样式,别忘了声明它......

<Window.Resources>
    <local:BytetoStringConverter x:Key="ColorConverter" />

----

    <Style TargetType="DataGridCell" x:Key="ColorPickerColorT0" 
       BasedOn="{StaticResource CommonCell}">
        <Setter Property="Background" Value="{Binding Path=ColorT0, Converter={StaticResource ColorConverter} }" />
        <Setter Property="Foreground" Value="Transparent"/>
        <Setter Property="Width" Value="35"></Setter>
    </Style>

----
</Window.Resources>

转换器:

public class BytetoStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        byte[] val = BitConverter.GetBytes((Int32)value);
        //val = (byte[]) value;
        return Color.FromArgb(val[3], val[2], val[1], val[0]).ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        byte[] val = new byte[4];
        Color c = (Color)value;
        val[0] = c.A;
        val[1] = c.R;
        val[2] = c.G;
        val[3] = c.B;

        return val;
    }
}

0 个答案:

没有答案