WPF 网格验证
本文关键字:验证 网格 WPF | 更新日期: 2023-09-27 18:36:58
我有可编辑的网格,它绑定了GridRow
集合(自定义类,网格的描述行)。 GridRow
具有属性Parameter
(int)
,应由用户编辑。所以简单的验证工作正常:I不能在此字段中插入"文本"或其他内容。但我需要对整个网格进行验证。在网格上的第 Parameter
列中只能有一个符号"1"、两个"2"、三个"3"、两个"5"。因此,例如,如果我已经插入网格值"1,2,3"并尝试插入"1",则应用程序应向我显示验证消息。我尝试用IDataErrorInfo
做到这一点,但我无法进入二传手整张桌子。
也许你会对我关于在 MVVM 中验证业务规则的博客文章感兴趣?
它允许您从 ViewModel 附加模型验证代码,并应允许您完成要执行的操作。
public class GridViewModel
{
// Kept this generic to reduce code here, but it
// should be a full property with PropertyChange notification
public ObservableCollection<GridRowModel> GridRows{ get; set; }
public UsersViewModel()
{
GridRows = GetGridRows();
// Add the validation delegate to the UserModels
foreach(var row in GridRows)
user.AddValidationErrorDelegate(ValidateGridRow);
}
// User Validation Delegate to verify UserName is unique
private string ValidateGridRow(object sender, string propertyName)
{
if (propertyName == "Parameter")
{
var row = (GridRow)sender;
var existingCount = GridRows.Count(p =>
p.Parameter == row.Parameter && p != row);
switch(row.Parameter)
{
case 1:
if (existingCount >= 0)
return string.Format("{0}s are already taken", row.Parameter);
case 2: case 5:
if (existingCount >= 1)
return string.Format("{0}s are already taken", row.Parameter);
case 3:
if (existingCount >= 2)
return string.Format("{0}s are already taken", row.Parameter);
}
}
return null;
}
}
我修复了订阅"CellVaildate"事件的问题。