c# - 将整数绑定到用颜色填充矩形
问题描述
我的 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;
}
}
我在这里做错了什么?
解决方案
推荐阅读
- node.js - 向不同端点发出请求时,Twitter 的速率限制如何发挥作用?
- python - Python:根据列中的最大长度向行中的元素添加空格时遇到问题
- ios - 在 UICollectionViewFlowLayout 子类中在哪里重新计算静态 itemSize?
- apache - Apache 因自分配 SSL 和 MAMP Pro 5 而失败
- jsf - iCal4j 和使用 primefaces p.schedule
- linux - cd 到虚拟环境而不是采购它
- django - 将 json 作为 celery 任务的一部分插入 postgres
- laravel - Laravel - 使用相同的 v-model 选择表单
- reporting-services - 在 SSRS 中动态传递文本框值
- javascript - Javascript-锁定字符串以防止其他方法更改它