通过使用属性指定的索引来更改ListViewItem背景颜色

时间:2019-02-11 18:03:19

标签: c# wpf datatrigger

我是WPF的新手,我有一个属性,它定义了int,它是元素的索引,用于更改ListView中的背景色,但正在更改所有{ ListViewItem,这里是我的代码:

<ListView AlternationCount="2147483647" x:Name="listView1" HorizontalAlignment="Left" Height="295" Margin="10,10,0,0" VerticalAlignment="Top" Width="380" Padding="0" HorizontalContentAlignment="Center" BorderThickness="1" IsSynchronizedWithCurrentItem="False" SelectionMode="Single" ScrollViewer.CanContentScroll="True">
                    <ListView.ItemContainerStyle>
                        <Style TargetType="{x:Type ListViewItem}">
                            <Setter Property="ContextMenu" Value="{StaticResource ListViewItemContexMenuKey}"/>

                            <Style.Triggers>
                                <DataTrigger Value="True">
                                    <DataTrigger.Binding>
                                        <MultiBinding Converter="{StaticResource IndexConverter}">
                                            <Binding Path="AlternationIndex" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=ItemsControl}"/>
                                            <Binding Path="TargetIndex" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=Window}"/>
                                        </MultiBinding>
                                    </DataTrigger.Binding>
                                    <Setter Property="Background" Value="#FFFF7171"/>
                                </DataTrigger>
                            </Style.Triggers>

                        </Style>
                    </ListView.ItemContainerStyle>
   </ListView>

这里是IndexConverter

public class IndexConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        int index = (int)values[0];
        int targetIndex = (int)values[1];

        Console.WriteLine($"Index: {index}, TargetIndex: {targetIndex}");
        return index == targetIndex;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

IndexConverter.Convert中,局部变量索引为AlternationIndex,并且始终返回0。

我不知道为什么这种行为,当使用触发器时,它可以正确工作,但是您不能使用触发器进行绑定。

<Trigger Property="ItemsControl.AlternationIndex" Value="1">
        <Setter Property="Background" Value="#FFFF7171"/>
</Trigger>

1 个答案:

答案 0 :(得分:2)

@elgonzo指出,ItemsControl.AlternationIndexattached property,您应该这样绑定:

<Binding Path="(ItemsControl.AlternationIndex)" 
         RelativeSource="{RelativeSource Self}"/>

请注意路径周围的括号。