验证ListBoxItem而不是ListBox INotifyDataErrorInfo

问题描述 投票:0回答:1

我在这里尝试了解决方案:Validating a ListBoxItem rather than a ListBoxWPF ListBox ErrorTemplateWPF 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;
        }
    }

无论我怎么努力,我都会始终将整个列表框突出显示,并在出现错误时用红色边框包围(而不是出现错误的listboxitem)我的代码有什么问题吗?

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

wpf xaml listboxitem inotifydataerrorinfo
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.