【问题标题】:ValueConverter for Background Color背景颜色的值转换器
【发布时间】:2014-12-28 14:44:44
【问题描述】:

我有一个预测类。字段类型之一是枚举:

enum GeneralForecast
{
    Sunny,
    Rainy,
    Snowy,
    Cloudy,
    Dry
}

class Forecast
{
    public GeneralForecast GeneralForecast { get; set; }
    public double TemperatureHigh { get; set;  }
    public double TemperatureLow { get; set; }
    public double Percipitation { get; set; }
}

我在 ListBox 上显示预测列表,我想根据 GeneralForecast 设置 ListBox 中项目的 BackgroundColor。

所以我创建了转换器:

类 GeneralForecastToBrushConverter : IValueConverter {

    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var gf = (GeneralForecast) value;
        switch (gf) 
        {
            case GeneralForecast.Cloudy:
                return "FF1D1D1D";
            case GeneralForecast.Dry:
                return "55112233";
            case GeneralForecast.Rainy:
                return "88FF5522";
            case GeneralForecast.Snowy:
                return "9955FF22";
            case GeneralForecast.Sunny:
                return "FF11FF99";
        }
        return "FFFFFFFF";
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

这是我的 XAML:

<Page.Resources>
    <local:GeneralForecastToBrushConverter x:Key="gf2color"/>
</Page.Resources>

<ListBox ItemsSource="{Binding}" Grid.Row="2" HorizontalAlignment="Stretch">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Border Margin="4" BorderBrush="Black" Padding="4" 
                        BorderThickness="2" 
                        Background="{Binding GeneralForecast, Converter={StaticResource gf2color}}">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock FontSize="20" FontWeight="Bold" 
                                   Text="{Binding GeneralForecast}"/>                            
                    </StackPanel>
                </Border>
            </DataTemplate>                
        </ListBox.ItemTemplate>
    </ListBox>

如果我调试我的转换器,我可以看到它返回不同的颜色,但我的所有项目都具有相同的颜色。为什么?

【问题讨论】:

    标签: wpf windows-8.1


    【解决方案1】:

    当你在 XAML 中写这样的东西时:

    <Button Background="#FF11111" />
    

    Xaml 解析器会在运行时将该字符串转换为其等效颜色。

    但是当你以某种方式在 C# 中分配颜色时,你可能不会将颜色设置为字符串。

    相反,您应该使用 SolidColorBrush 实例。

    所以返回一些变量是Brush,例如纯色或渐变色画笔。

    如果需要任何其他信息,请告诉我。

    【讨论】:

      猜你喜欢
      • 2015-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多