[英]Alternate ListBox row colors
我正在嘗試使用替代行顏色來設計此ListBox的樣式:
<ListBox x:Name="listBox" Background="{x:Null}" SelectionChanged="listBox_SelectionChanged" >
<ListBox.Resources>
<local:AltBackgroundConverter x:Name="AltBackgroundConverter" />
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0" Height="50" Background="{Binding Converter={StaticResource AltBackgroundConverter}}" >
<TextBlock Text="{Binding Titulo}" Style="{StaticResource ListViewItemTextBlockStyle}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
這是AltBackgroundConverter.cs
:
public class AltBackgroundConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (!(value is int)) return null;
int index = (int)value;
if (index % 2 == 0)
return Colors.White;
else
return Colors.Gray;
}
// No need to implement converting back on a one-way binding
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
顯然,它不起作用,因為我沒有實現如何將行號綁定到轉換器。 如您所見,我正在綁定整個ListBox項。
我認為解決方案應該非常簡單,但是我找不到。
您的解決方案現在有幾個問題。
您綁定到列表項,而轉換器需要一個整數來確定某項是偶數還是奇數。 根據您的屏幕截圖,您應該對其進行更改,如下所示:
Background =“ {Binding Numero,Converter = {StaticResource AltBackgroundConverter}}”“
您的轉換器返回一個顏色,而Background
是一個畫筆,因此您可以像這樣修復它:
public class AltBackgroundConverter : IValueConverter { private Brush whiteBrush = new SolidColorBrush(Colors.White); private Brush grayBrush = new SolidColorBrush(Colors.Gray); public object Convert(object value, Type targetType, object parameter, string language) { if (!(value is int)) return null; int index = (int)value; if (index % 2 == 0) return whiteBrush; else return grayBrush; } // No need to implement converting back on a one-way binding public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } }
一切應該在此時開始,但是突出顯示只會突出顯示文本,而不是整個行。 這是解決問題的方法:
<ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter> </Style> </ListBox.ItemContainerStyle>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.