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

问题描述 投票:0回答:1

我是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>
c# wpf datatrigger
1个回答
2
投票

正如@elgonzo所指出的,ItemsControl.AlternationIndex是一个attached property,你应该像这样绑定:

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

请注意路径周围的括号。

© www.soinside.com 2019 - 2024. All rights reserved.