【发布时间】: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