首页 > 解决方案 > 将整数绑定到用颜色填充矩形

问题描述

我的 WPF 应用程序中有一个矩形,我想用颜色填充。此颜色基于我的代码中的值。该值可以从 0 到 1023。

如果值为 0,我希望将 Rectangle 填充为黑色,直到值为 1023 为全白色。

我知道我需要某种转换器来做到这一点,但我看不出我做错了什么,我对 IValueConverters 没有太多经验。

在我的 XAML 代码中,我有以下代码:

<Page.Resources>
    <root:IntegerToColorConverter x:Key="integerColorConverter" />
</Page.Resources>

而转换器转换器在 XAML 代码中是这样使用的:

<Grid>
    <Rectangle Grid.Column="1" Grid.Row="1" Fill="{Binding Path=LightDiodeValue, Converter={StaticResource integerColorConverter}}" Width="10" Height="10" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,60"/>
</Grid>

当显示页面时,调用 IntegerToColorConverter 并且我可以看到它使用我期望的值创建 SolidBrush 然后返回它,但由于某种原因,矩形没有填充这个 SolidBrush 。

转换器看起来像这样:

class IntegerToColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            int iValue = (int)value;
            iValue = iValue * 255 / 1024; //Convert from  1024 range to 255 range
            Color customColor = Color.FromArgb(255, iValue, iValue, iValue);
            SolidBrush integerBrush = new SolidBrush(customColor);

            return integerBrush ;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            SolidBrush brush = (SolidBrush)value;

            int iValue = (brush.Color.R + brush.Color.G + brush.Color.B) * 1024 / 255 / 3;
            return iValue;
        }
    }

我在这里做错了什么?

标签: c#wpfxaml

解决方案


推荐阅读