0

First of all I apologise for my bad english.

I have xml binded to a listview, where each row stands for one person. I want row's background color blue or pink depending on sex element in xml. I've created style with triggers, but they seems to check only first xml node and all rows are colored same as 1st row. Xml element sex is 0 for male, 1 for female.

One DataTrigger (second is similar):

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

This is xml and style binding to listview (data is XmlDataProvider):

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

And this is style header:

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

Thanks for help!

4

1 回答 1

0

You should use a ValueConverter for this.

You bind the background of the datatemplate to the gender. Then you create a value converter class like this:

   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();
    }
}

This value converter you then add to your resources like this:

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

And in your datatemplate:

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

</Stackpanel>
于 2013-03-30T19:32:52.987 回答