根据索引更改 ListBoxItem 的颜色
Changing color of ListBoxItem based on index
我正在尝试根据索引值更改 ListBox 中其中一项的前景(文本)颜色。例如,如果索引为 1,则索引 1 处的项目将具有与所有其他项目不同的文本颜色。索引不是列表选择索引,而是我自己的值。
我在 Google 上四处搜索,发现了一些使用 AlternationIndex 的想法,但我无法让它发挥作用。转换器正在接收 0(零)或 DependencyProperty#Unset 用于 AlternationIndex 绑定。
这是我的代码:
<ListBox x:Name="videoList" SelectionMode="Single" AlternationCount="{Binding Mode=OneWay, Path=Items.Count}" Grid.Column="1" SelectionChanged="videoList_SelectionChanged">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<DataTrigger Value="True">
<DataTrigger.Binding>
<MultiBinding Mode="OneWay" Converter="{StaticResource EqualityConverter}">
<MultiBinding.Bindings>
<Binding ElementName="videoWindow" Mode="OneWay" Path="VideoIndex" />
<Binding RelativeSource="{RelativeSource AncestorType=ListBoxItem}" Path="(ItemsControl.AlternationIndex)" />
</MultiBinding.Bindings>
</MultiBinding>
</DataTrigger.Binding>
<DataTrigger.Setters>
<Setter Property="Foreground" Value="Blue" />
</DataTrigger.Setters>
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
对于我尝试过的 RelativeSource:Self、TemplatedParent 和 AncestorType=ListBoxItem。 我还尝试了很多不同的路径值组合。
我无法让它工作。有什么建议吗?
解决方案:在Clemens的帮助下,原来是因为ListBox AlternationCount的绑定不正确。糟糕!
<ListBox x:Name="videoList"
SelectionMode="Single"
AlternationCount="{Binding RelativeSource={RelativeSource Self}, Mode=OneWay, Path=Items.Count}"
Grid.Column="1"
SelectionChanged="videoList_SelectionChanged">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<DataTrigger Value="True">
<DataTrigger.Binding>
<MultiBinding Mode="OneWay" Converter="{StaticResource EqualityConverter}">
<MultiBinding.Bindings>
<Binding ElementName="videoWindow" Mode="OneWay" Path="VideoIndex" />
<Binding RelativeSource="{RelativeSource Self}" Path="(ItemsControl.AlternationIndex)" />
</MultiBinding.Bindings>
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="Foreground" Value="Blue" />
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
它适用于 RelativeSource Self
和足够大的 AlternationCount
,例如int.MaxValue
.
<ListBox AlternationCount="2147483647" ...>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<DataTrigger Value="True">
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource EqualityConverter}">
<MultiBinding.Bindings>
<Binding ElementName="videoWindow"
Path="VideoIndex"/>
<Binding RelativeSource="{RelativeSource Self}"
Path="(ItemsControl.AlternationIndex)"/>
</MultiBinding.Bindings>
</MultiBinding>
</DataTrigger.Binding>
<DataTrigger.Setters>
<Setter Property="Foreground" Value="Blue"/>
</DataTrigger.Setters>
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>