Вот что я пытался сделать, чтобы получить градиентный фон в элементе списка (List) в зависимости от значения int объекта с данными
Мой объект в упрощенном виде:
public class Item {
public string name { get; set; }
public string address { get; set; }
public int highlight { get; set; }
}
Попытка конвертера:
Использование этого конвертера:
public class BusinessTypeToBackgroundConverter : IValueConverter
{
private static readonly LinearGradientBrush NormalBkg = new LinearGradientBrush
{
StartPoint = new Point(0, 0),
EndPoint = new Point(0, 1),
GradientStops = new GradientStopCollection
{
new GradientStop {Color = Util.GetColorFromHex("#4ce6e6e6")},
new GradientStop {Color = Util.GetColorFromHex("#ffe6e6e6")}
}
};
private static readonly LinearGradientBrush HighlightedBkg = new LinearGradientBrush
{
StartPoint = new Point(0, 0),
EndPoint = new Point(0, 1),
GradientStops = new GradientStopCollection
{
new GradientStop {Color = Util.GetColorFromHex("#4cffffcc")},
new GradientStop {Color = Util.GetColorFromHex("#ffffffcc")}
}
};
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
switch ((int)value)
{
case 1:
return HighlightedBkg;
case 2:
return NormalBkg;
default:
return NormalBkg;
}
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException("BusinessTypeToBackgroundConverter ConvertBack Method Not Implemented");
}
}
И этот пункт шаблона
<ListBox
Name="lstResults"
ItemContainerStyle="{StaticResource ListBoxItemStyle1}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Background="{Binding highlight, Converter={StaticResource myConverter}}">
<StackPanel>
<TextBlock Text="{Binding name}" TextWrapping="Wrap" FontSize="24" FontWeight="Bold" Foreground="Black"/>
<TextBlock Text="{Binding address}" TextWrapping="Wrap" FontSize="24" Foreground="Black" />
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Код, стоящий за попыткой
Добавлено свойство "LinearGradientBrush background" для моего объекта Item
public LinearGradientBrush background
{
get
{
if (highlight == 1) return HighlightedBkg;
else return NormalBkg;
}
}
В обоих случаях к списку элементов (фону сетки) применяется только начальный цвет градиента. В итоге я получаю сплошной цвет :)
Есть ли в любом случае установить фон градиента от кода и не использовать нотацию XAML:
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStopCollection>
<GradientStop Color="#ff444444" Offset="0" />
<GradientStop Color="#ff000000" Offset="1" />
</GradientStopCollection>
</LinearGradientBrush>