我是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>
正如@elgonzo所指出的,ItemsControl.AlternationIndex
是一个attached property,你应该像这样绑定:
<Binding Path="(ItemsControl.AlternationIndex)"
RelativeSource="{RelativeSource Self}"/>
请注意路径周围的括号。