我在这里尝试 了解决方案:验证 ListBoxItem 而不是 ListBox 和 WPF ListBox ErrorTemplate 和 WPF INotifyDataErrorInfo highlight ListBoxItem
我有一个列表框
<ListBox ItemsSource="{Binding ViewNewPanelsPairs}" ItemTemplate="{StaticResource LevelsTemplate}" Style="{StaticResource PanelsListBox}"
SelectionMode="Single" Margin="10" SelectedItem="{Binding CurrentViewNewPanelsPair, ValidatesOnNotifyDataErrors=True}" ItemContainerStyle="{StaticResource LevelItemTemplate}"/>
使用以下项目模板和 itemcontainerstyle
<DataTemplate x:Key="LevelsTemplate" DataType="{x:Type VM:ViewNewPanelsPair}">
<CheckBox VerticalContentAlignment="Center" Content="{Binding View.Name}"
IsChecked="{Binding IsViewPanelsNotEmpty, Mode=OneWay}"
IsHitTestVisible="False"
IsEnabled="{Binding RelativeSource={RelativeSource Self}, Path=IsChecked}"/>
</DataTemplate>
<Style x:Key="LevelItemTemplate" TargetType="ListBoxItem" >
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="Transparent" />
<Style.Triggers>
<DataTrigger Binding="{Binding Validation.HasErrors}" Value="True">
<Setter Property="BorderBrush" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
和以下验证(实现 INotifyDataErrorInfo)
public ViewNewPanelsPair CurrentViewNewPanelsPair
{
get => currentViewNewPanelsPair;
set
{
Set(() => CurrentViewNewPanelsPair, ref currentViewNewPanelsPair, value);
ValidateProperty(nameof(CurrentViewNewPanelsPair));
}
}
和
protected void ValidateProperty(string PropertyName)
{
ClearErrors(PropertyName);
switch (PropertyName)
{
case nameof(ViewNewPanelsPairs):
if (!ViewNewPanelsPairs.Any(x => x.IsViewPanelsNotEmpty))
{
AddError(PropertyName, "At least one view must have new panels");
}
break;
case nameof(CurrentViewNewPanelsPair):
if (CurrentViewNewPanelsPair.NewPanels.Count != 0 && CurrentViewNewPanelsPair.NewPanels.Count!=ViewNewPanelsPair.OldPanels.Count)
{
AddError(PropertyName, "New Panels must be equal to Old Panels");
}
break;
}
}
无论我多么努力,我总是让整个列表框突出显示,并在错误时用红色边框包围(不是有错误的列表框项)我的代码有问题吗?
注意:我调试了代码以确保确实存在错误并且确实存在并且它显示为整个列表框周围的边框