0

我在这里尝试 了解决方案:验证 ListBoxItem 而不是 ListBoxWPF 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;
        }
    }

无论我多么努力,我总是让整个列表框突出显示,并在错误时用红色边框包围(不是有错误的列表框项)我的代码有问题吗?

注意:我调试了代码以确保确实存在错误并且确实存在并且它显示为整个列表框周围的边框

4

1 回答 1

0

当我在我的模型类“ViewNewPaanelsPair”上实现 INotifyDataErrorinfo 并将 itemscontrolcontainer 的数据触发器绑定到引发这样的错误的属性时,它起作用了

<DataTrigger Binding="{Binding NewPanels}" > <Setter Property="BorderBrush" Value="Red"/> </DataTrigger>

感谢@Andy 的帮助

于 2019-10-29T19:49:01.733 回答