【问题标题】:WPF - Highlighting rows in listview with binded XMLWPF - 使用绑定的 XML 突出显示列表视图中的行
【发布时间】:2013-03-21 06:15:26
【问题描述】:

首先我为我糟糕的英语道歉。

我将 xml 绑定到一个列表视图,其中每一行代表一个人。我想要行的背景颜色为蓝色或粉红色,具体取决于 xml 中的性别元素。我用触发器创建了样式,但它们似乎只检查第一个 xml 节点,并且所有行的颜色都与第一行相同。 xml元素性别为男性为0,女性为1。

一个DataTrigger(第二个类似):

<DataTrigger Binding="{Binding Source={StaticResource Data}, XPath=People/Person/Sex}" Value="0">
    <Setter Property="Background" Value="{StaticResource MaleBrush}" />
</DataTrigger>

这是 xml 和样式绑定到 listview(数据是 XmlDataProvider):

<ListView ... ItemsSource="{Binding Source={StaticResource Data}, XPath=People/Person}" ItemContainerStyle="{StaticResource SexStyle}">

这是样式标题:

<Style x:Key="SexStyle"  TargetType="{x:Type ListViewItem}">

感谢您的帮助!

【问题讨论】:

    标签: c# wpf xml listview data-binding


    【解决方案1】:

    您应该为此使用 ValueConverter。

    您将数据模板的背景绑定到性别。 然后你创建一个像这样的值转换器类:

       public sealed class GenderToBackgroundConverter : IValueConverter
       {
    
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is string) {
                if (Convert.ToString(value) == "m") {
                    return Colors.Blue;
                } else {
                    return Colors.Pink;
                }
            }
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    然后您可以将此值转换器添加到您的资源中,如下所示:

    <local:GenderToBackgroundConverter x:Key="GenderToBackgroundConverter" />
    

    在你的数据模板中:

    <Stackpanel Background={Binding Sex, Converter={StaticResource GenderToBackgroundConverter}}">
    
    </Stackpanel>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-19
      • 2013-09-07
      • 2012-06-10
      • 1970-01-01
      • 1970-01-01
      • 2013-12-22
      • 2012-11-21
      • 1970-01-01
      相关资源
      最近更新 更多