ValueConverter for Background Color

陌路散爱 提交于 2019-12-11 20:18:48

问题


I have a Forecast class. One of the field's type is Enum:

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; }
}

I display list of forecasts on the ListBox and I want to set the BackgroundColor of the item in the ListBox depend on GeneralForecast.

So I have created Converter:

class 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();
    }
}

Here is my 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>

If I debug my Converter I can see that it returns different colors, but I have all items the same color. Why ?


回答1:


When you write something like this in XAML:

<Button Background="#FF11111" />

The Xaml parser will convert that string to its equivalent color at runtime.

But when you assign color in C# somehow, you may not set the color as string.

Instead you should use something like SolidColorBrush instances.

So return some variable which is Brush, such as solid or gradient color brushes.

Let me know if any other information is needed.



来源:https://stackoverflow.com/questions/27674233/valueconverter-for-background-color

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!