编辑后WPF Datagrid行验证错误未清除

men*_*owo 6 c# validation wpf datagrid

在WPF中使用DataGrid,我试图通过INotifyDataErrorInfo使用错误验证时获得正确的行为.

我有一个实现该接口的类的ObservableCollection,一个绑定到DataGrid的集合.出现错误时,单元格将显示红色边框,行将显示红色!在前.全部默认,都很好.当还在编辑时,当错误消失时,红色边框和红色!都会消失.到现在为止还挺好!

但是,当我离开行(通过键盘输入/ Tab或鼠标),然后返回它然后删除错误,红色单元格边框消失,但红色!停留.

我知道之前已经提出过这个问题,例如:WPF DataGrid验证错误未清除.但是,除了完全隐藏行验证错误之外,那里的解决方案无法解决此问题.(其中,结合第二个答案,这里也很好......)

或者是我的问题而不是用户能够离开单元格的编辑模式,即使有验证错误?最好,我想限制这一点,并在进一步编辑之前先强制解决错误,但我不知道如何在没有大量代码的情况下强制执行此操作...

这是XML(RowValidationErrorTemplate来自这里:链接):

<UserControl x:Class="CustomDG"
             ...etc...
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300"
             d:DataContext="{d:DesignInstance Type=viewmodels:TestViewModel}">
    <Grid>
        <DataGrid
            ItemsSource="{Binding Path=testCollection}" AutoGenerateColumns="False"
            RowHeight="18" CanUserResizeRows="False" RowHeaderWidth="18" >
            <DataGrid.RowValidationErrorTemplate>
              <ControlTemplate>
                <Grid Margin="0,-2,0,-2"
                    ToolTip="{Binding RelativeSource={RelativeSource
                    FindAncestor, AncestorType={x:Type DataGridRow}},
                    Path=(Validation.Errors)[0].ErrorContent}">
                    <Ellipse StrokeThickness="0" Fill="Red" 
                        Width="{TemplateBinding FontSize}" 
                        Height="{TemplateBinding FontSize}" />
                    <TextBlock Text="!" FontSize="{TemplateBinding FontSize}" 
                        FontWeight="Bold" Foreground="White" 
                        HorizontalAlignment="Center"  />
                    </Grid>
                </ControlTemplate>
            </DataGrid.RowValidationErrorTemplate>-->

            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Path=Name, 
                    ValidatesOnNotifyDataErrors=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >
                </DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

His*_*ham 5

您需要在行提交或取消编辑后使用空字符串引发notifyPropertyChanged以刷新 DataBinding From 对象,这将刷新您的界面,如下所示:

RaiseNotifyPropertyChanged(""); 
Run Code Online (Sandbox Code Playgroud)

  • 对我不起作用。如果任何单元格中存在错误,每次我离开“添加新行”编辑时,DataGridRow 上的 Validation.ErrorsProperty 都会累积错误。可怕的机制。 (2认同)