假设您的视图模型中的项目集合是MyItemsCollection,并且您的项目类型是MyItem。将属性 TargetItem 属性添加到您的视图模型以标识要突出显示的项目。
private MyItem _highlightedItem;
public MyItem HighlightedItem
{
get => _highlightedItem;
set
{
if (_highlightedItem!= value)
{
_highlightedItem = value;
OnPropertyChanged();
}
}
}
创建一个简单的多值转换器,它比较对象是否相等并返回bool。
public class EqualityToBooleanConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values[0] == values[1];
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new InvalidOperationException("This is a one-way conversion.");
}
}
您可以将其添加到您的ItemsControl 的资源字典中。
<ItemsControl ItemsSource="{Binding MyItemsCollection}" ...>
<ItemsControl.Resources>
<local:EqualityToBooleanConverter x:Key="EqualityToBooleanConverter"/>
</ItemsControl.Resources>
<!-- ...your other code. -->
</ItemsControl>
根据您的视图模型中的HighlightedItem 属性,在您的DataTemplate 中创建一个DataTrigger 以突出显示ToggleButton。
<DataTemplate DataType="{x:Type local:MyItem}">
<ToggleButton Content="{Binding Id}"
IsChecked="{Binding Enabled">
<ToggleButton.Style>
<Style TargetType="{x:Type ToggleButton}"
BasedOn="{StaticResource {x:Type ToggleButton}}">
<Style.Triggers>
<DataTrigger Value="True">
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource EqualityToBooleanConverter}">
<Binding/>
<Binding Path="DataContext.HighlightItem" RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}"/>
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="Background" Value="Yellow"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ToggleButton.Style>
</ToggleButton>
</DataTemplate>
现在您只需将HighlightedItem 设置为您通过其在视图模型中的MyItemsCollection 中的索引访问的目标项。
HighlightedItem = MyItemsCollection[24];
请注意,如果要突出显示的项目实际上是选定的项目,那么请考虑使用Selector 控件,例如ListBox。然后你可以使用它的容器的IsSelected 属性。