/// <summary> /// 获取DataGrid的所有行是否存在验证错误。 /// </summary> /// <param name="dg">要检查的DataGrid实例</param> /// <returns>true 有错,false 无错</returns> public static bool GetDataGridRowsHasError(DataGrid dg) { bool hasError = false ; for ( int i = 0; i < dg.Items.Count; i++) { DependencyObject o = dg.ItemContainerGenerator.ContainerFromIndex(i); hasError = Validation.GetHasError(o); if (hasError) { break ; } } return hasError; } |
判断有验证错误 就不执行提交。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
/// <summary> /// 获取DataGrid的第一个被发现的验证错误结果。 /// </summary> /// <param name="dg">被检查的DataGrid实例。</param> /// <returns>错误结果。</returns> public static ValidationError GetDataGridRowsFirstError(DataGrid dg) { ValidationError err= null ; for ( int i = 0; i < dg.Items.Count; i++) { DependencyObject o = dg.ItemContainerGenerator.ContainerFromIndex(i); bool hasError = Validation.GetHasError(o); if (hasError) { err = Validation.GetErrors(o)[0]; break ; } } return err; } /// <summary> /// 执行检查DataGrid,并提示第一个错误。重新定位到错误单元格。 /// </summary> /// <param name="dg">被检查的DataGrid实例。</param> /// <returns>true 有错并定位,false 无错、返回</returns> public static bool ExcutedCheckedDataGridValidation(DataGrid dg) { ValidationError err = GetDataGridRowsFirstError(dg); if (err != null ) { string errColName = ((System.Windows.Data.BindingExpression)err.BindingInError).ParentBinding.Path.Path; DataGridColumn errCol = dg.Columns.Single(p => { if (((Binding)((DataGridTextColumn)p).Binding).Path.Path == errColName) return true ; else return false ; }); //string errRow = ((DataRowView)((System.Windows.Data.BindingExpression)err.BindingInError).DataItem)["SWH"].ToString(); //dg.Items.IndexOf(((System.Windows.Data.BindingExpression)err.BindingInError).DataItem); dg.SelectedItem = ((System.Windows.Data.BindingExpression)err.BindingInError).DataItem; int errRowIndex = dg.SelectedIndex; MessageBox.Show( string .Format( "第\"{0}\"行 的\"{1}\"列的单元格数据不合法(以红色标出),请填写正确后再执行其他操作。" , errRowIndex + 1, errCol.Header), "系统消息" , MessageBoxButton.OK, MessageBoxImage.Warning); dg.CurrentCell = new DataGridCellInfo(dg.SelectedItem, errCol); if (!((DataRowView)dg.CurrentItem).IsEdit) { ((DataRowView)dg.CurrentItem).BeginEdit(); } TextBox txt = dg.CurrentColumn.GetCellContent(dg.CurrentItem) as TextBox; txt.Focus(); return true ; } else { return false ; } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2017-03-01 C#中4种深拷贝方法介绍
2017-03-01 浅谈.net平台下深拷贝和浅拷贝
2017-03-01 asp.net源程序编译为dll文件并调用的实现过程