一個一個LinearGradientBrush這裏是我試過到目前爲止取決於databinded對象設置列表框項目背景根據的ItemSource Databinded價值
我對象的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背景」 屬性來我的項目對象
public LinearGradientBrush background
{
get
{
if (highlight == 1) return HighlightedBkg;
else return NormalBkg;
}
}
在這兩種情況下,只有在開始顏色的漸變應用於listItem(網格背景)。所以我最終用純色:)
反正是有設定背景TI的代碼,而不是使用XAML標記的漸變:
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStopCollection>
<GradientStop Color="#ff444444" Offset="0" />
<GradientStop Color="#ff000000" Offset="1" />
</GradientStopCollection>
</LinearGradientBrush>
就是這樣......非常感謝! – linakis 2011-05-26 10:51:30
對於我所描述的問題,使用BoolToBrushConverter實際上是一個更好的解決方案,但事實是,我從供應商那裏獲得我的「物品」,並且他可能擁有超過2個州列表項,例如贊助/免費/高亮顯示。再次感謝,我喜歡閱讀! – linakis 2011-05-26 10:58:24
@Bororo:那麼請參閱下一篇博客文章:http://geekswithblogs.net/codingbloke/archive/2010/06/09/yet-another-blog-about-ivalueconverter.aspx我將bool轉換器概念向前推進了一步到一個枚舉轉換器。 – AnthonyWJones 2011-05-26 11:34:28