1

我有可编辑的网格,它绑定在GridRow(自定义类,描述的网格行)的集合上。 GridRow有属性Parameter (int),应该由用户编辑。如此简单的验证工作正常:我无法在此字段中插入“文本”或其他内容。但我需要在整个网格上进行验证。在网格上的列Parameter中只能有一个符号'1',两个'2',三个'3',两个'5'。因此,例如,如果我已经插入网格值“1,2,3”并尝试插入“1”,应用程序应该向我显示验证消息。我尝试用 来做到这一点IDataErrorInfo,但我无法进入整张桌子。

4

2 回答 2

1

也许您会对我的一篇关于在 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;
    }
}
于 2012-06-13T16:06:40.580 回答
1

我解决了订阅“CellVaildate”事件的问题。

于 2012-06-14T06:44:19.723 回答