如何解决如何在ItemsControl WPF中突出显示特定的Content元素项?
我有ItemControl,它显示切换按钮的列表,按钮名称通过绑定内容名称以数字显示。 我需要说的是要突出显示数字24的“切换”按钮。 有什么办法可以通过索引位置获取Itemscontrol并在XAML触发器中突出显示背景。 例如:点击按钮时,我想突出显示id = 9的切换按钮。
<itemsControl>
<datatemplate>
<radtoggleButton content={binding id} ischecked={binding enabled}>
</datatemplate>
</itemsControl>
有没有办法像下面这样动态命名数据模板控件项?
解决方法
比方说,您在视图模型中的项目集合为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,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
属性。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。