C# 交替列表框行颜色

C# 交替列表框行颜色,c#,xaml,listbox,windows-runtime,windows-phone,C#,Xaml,Listbox,Windows Runtime,Windows Phone,我正在尝试使用其他行颜色来设计此列表框: <ListBox x:Name="listBox" Background="{x:Null}" SelectionChanged="listBox_SelectionChanged" > <ListBox.Resources> <local:AltBackgroundConverter x:Name="AltBackgroundConverter" /> </ListBox.Res

我正在尝试使用其他行颜色来设计此列表框:

<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>
显然,它不起作用,因为我没有实现如何将行号绑定到转换器。如您所见,我正在绑定整个ListBox项


我认为解决方案应该非常简单,但我找不到。

您的解决方案现在有几个问题

绑定到列表项,而转换器需要一个整数来确定项是偶数还是奇数。根据您的屏幕截图,您应该将其更改为如下所示:

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();
    }
}
背景={Binding Numero,Converter={StaticResource AltBackgroundConverter}

转换器返回一种颜色,而背景是画笔,因此您可以按如下方式修复它:

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>

您没有绑定背景属性中的属性。尝试将绑定路径设置为希望值位于转换器中的属性。或者考虑这个方法,这就是问题所在。我不知道该给哪个属性赋值,因为我找不到绑定行号的方法。此外,WinRT应用程序中不支持触发器。因此,这种方法不起作用:s