问题
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