首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >交替ListBox行颜色

问交替ListBox行颜色
EN

Stack Overflow用户
提问于 2014-04-07 23:44:21
回答 1查看 1.5K关注 0票数 1

我试图用可选行的颜色来设计这个ListBox:

代码语言:javascript
复制
<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

代码语言:javascript
复制
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项。

​

​

我认为解决办法应该很简单,但我找不到。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-08 05:18:44

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

  1. 绑定到列表项,而转换器需要一个整数来判断项是偶数还是奇数。根据您的屏幕截图,您应该更改它,如下所示: Background=“{绑定数值,Converter={StaticResource AltBackgroundConverter}”
  2. 转换器返回一个颜色,而Background是一个画笔,因此可以这样修复它: 公共类AltBackgroundConverter : IValueConverter {私有刷whiteBrush =新SolidColorBrush(Colors.White);私有刷grayBrush =新SolidColorBrush(Colors.Gray);公共对象转换(对象值、类型targetType、对象参数、字符串语言){ if (!(值为int))返回null;int索引=(Int)值;if (索引%2 == 0)返回whiteBrush;否则返回grayBrush;} //不需要在单向绑定的公共对象ConvertBack上实现转换(对象值、类型targetType、对象参数、字符串语言){抛出新的NotImplementedException();}
  3. 事情应该在此时开始工作,但是您的高亮显示只会突出显示文本而不是整行。你可以这样解决这个问题:
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22925080

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档