我有一个自定义用户控件,它位于我的 WPF 应用程序的主窗口中。窗口内是一个 ItemsControl。我创建了一种样式,以便可以绑定到作为我的视图模型类的属性的项目数组。该数组保存项目控件位置的索引。我应该补充一点,自定义控件是从 Shape 继承的,因此它具有 Stroke 属性。
public class ViewModel
{
...
public List<int> Selections
{
get => _selections;
set
{
if (value == _selections) return;
_selections = value;
OnPropertyChanged();
}
}
public HypercombState State
{
get => _state;
set
{
if (value == _state) return;
_state = value;
OnPropertyChanged();
}
}
}
这是负责识别视图模型是否保存选定索引的转换器。如果在数据绑定期间选择了项目,则如果应该返回 true。
public class ArrayContainsConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values[0] is not int id || values[1] is not List<int> array) return null;
return array?.Contains(id);
}
...
}
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Value="True">
<Condition.Binding>
<MultiBinding Converter="{StaticResource ArrayContainsConverter}">
<Binding Path="(ItemsControl.AlternationIndex)" RelativeSource="
{RelativeSource AncestorType=ContentPresenter}" />
<Binding Path="DataContext.Selections" />
</MultiBinding>
</Condition.Binding>
</Condition>
...
</MultiDataTrigger.Conditions>
<Setter Property="Stroke" Value="Chartreuse"></Setter>
</MultiDataTrigger>
</Style.Triggers>
Whenever the Selections or State properties change, I would like to update the ItemsControl so that there is a Stroke as a visual cue for the item's selected state when true. 如果我使用断点,我可以看到 Selections 属性发生变化,但是当列表更改时转换器没有触发。