wpf - 如何突出显示 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}>
解决方案
假设您的视图模型中的项目集合是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
以突出显示一个。ToggleButton
HighlightedItem
<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
它的容器的属性。
推荐阅读
- desire2learn - 使用 d2l 远程插件的问题(插入东西 cim)示例不起作用
- r - 迭代地从数据框中提取一个值 (R)
- data-structures - 如何以一种简单而难忘的方式记住有序遍历和前序遍历?
- javascript - 预计角服务 1-2
- php - 带有自定义文本的 WooCommerce woocommerce_review_order_after_cart_contents 钩子
- scala - Spark Streaming 和 Kafka 集成中的并行任务数
- java - PHP 哈希密码与 Java 哈希兼容
- python - python - 如何在另一个字典中制作一个字典,在另一个字典中创建一个字典
- html - 当上面的课程打开时,联系我们消失
- python-3.x - 如果使用 python 不存在字符串,如何忽略文件?