首页 > 解决方案 > 如何突出显示 ItemsControl WPF 中的特定内容元素项?

问题描述

我有显示切换按钮列表的 ItemControl,按钮名称通过绑定内容名称以数字显示。我需要什么,假设我想突出显示数字 24 的切换按钮。有什么方法可以通过索引位置获取 Itemscontrol 并突出显示 XAML 触发器中的背景。例如:当单击按钮时,我想突出显示 id=9 的切换按钮。

<itemsControl>
<datatemplate>
<radtoggleButton content={binding id} ischecked={binding enabled}>
</datatemplate>
</itemsControl>

有什么方法可以动态命名数据模板控件项,如下所示?<radtoggleButton Name={bindiing} content={binding id} ischecked={binding enabled}>

标签: wpfdata-bindingwpf-controlsprism

解决方案


假设您的视图模型中的项目集合是MyItemsCollection并且您的项目是 type 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>

根据您的视图模型中的属性,在您DataTrigger中创建一个DataTemplate以突出显示一个。ToggleButtonHighlightedItem

<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它的容器的属性。


推荐阅读