【发布时间】:2011-05-26 18:53:14
【问题描述】:
这是我迄今为止尝试在列表框项(列表)中实现渐变背景的方法,具体取决于数据绑定对象的 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>
尝试背后的代码
为我的 Item 对象添加了“LinearGradientBrush 背景”属性
public LinearGradientBrush background
{
get
{
if (highlight == 1) return HighlightedBkg;
else return NormalBkg;
}
}
在这两种情况下,只有渐变的起始颜色应用于 listItem(网格背景)。所以我最终得到了纯色:)
是否可以从代码中设置背景渐变而不使用 XAML 表示法:
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStopCollection>
<GradientStop Color="#ff444444" Offset="0" />
<GradientStop Color="#ff000000" Offset="1" />
</GradientStopCollection>
</LinearGradientBrush>
【问题讨论】:
标签: silverlight windows-phone-7