【问题标题】:WPF Datagrid row validation error not clearing after edit编辑后未清除 WPF Datagrid 行验证错误
【发布时间】:2015-10-04 06:57:07
【问题描述】:

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

我有一个实现该接口的类的 ObservableCollection,将该集合绑定到 DataGrid。出现错误时,单元格将有红色边框,行将有红色!在前。全部默认,一切正常。仍在编辑时,当错误消失时,红色边框和红色!两者都会消失。到目前为止,一切都很好!

但是,当我离开该行(通过键盘 Enter/Tab 或使用鼠标),然后返回它然后删除错误时,红色单元格边框消失,但红色 !留下来。

我知道以前有人提出过这个问题,例如这里:WPF DataGrid validation errors not clearing。但是,除了完全隐藏行验证错误之外,那里的解决方案并没有解决这个问题。 (其中,结合第二个答案here 之类的东西也很好......)

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

这里是 XML(RowValidationErrorTemplate 来自这里:link):

<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>

【问题讨论】:

    标签: c# wpf validation datagrid


    【解决方案1】:

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

    RaiseNotifyPropertyChanged(""); 
    

    【讨论】:

    • 如何实施?我可以举一个完整的例子吗?
    • 对我不起作用。如果任何单元格中有错误,每次我离开“添加新行”编辑时,DataGridRow 上的 Validation.ErrorsProperty 都会累积错误。可怕的机制。
    • 这就是我使用控件而不是 DataGrid 进行编辑的原因,它笨拙得难以想象!我只是看不出这种行为背后的逻辑,是错误还是什么?
    猜你喜欢
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 2011-06-29
    • 1970-01-01
    • 2011-11-10
    • 2012-12-09
    • 1970-01-01
    相关资源
    最近更新 更多