备用ListBox行颜色

时间:2014-04-07 23:44:21

标签: c# xaml listbox windows-runtime windows-phone

我试图用替代的行颜色来设计这个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项目。

enter image description here

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

1 个答案:

答案 0 :(得分:0)

目前您的解决方案存在一些问题。

  1. 您对列表项的绑定,而转换器需要一个整数来判断项是偶数还是奇数。根据你的截图,你应该改变它,看起来像这样:

    Background =&#34; {Binding Numero,Converter = {StaticResource AltBackgroundConverter}}&#34;

  2. 您的转换器会返回一种颜色,而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();
        }
    }
    
  3. 事情应该在这一点开始工作,但你的突出显示只会突出显示文本而不是整行。这就是你如何解决这个问题:

    <ListBox.ItemContainerStyle>
        <Style
            TargetType="ListBoxItem">
            <Setter
                Property="HorizontalContentAlignment"
                Value="Stretch"></Setter>
        </Style>
    </ListBox.ItemContainerStyle>