0

我遇到了从代码隐藏执行验证的问题。我的数据显示在数据网格中。其中一列(类型)是下拉菜单,当下拉菜单更改时,它会触发 DropDownClosed 事件,该事件在后面的代码中处理。

我想要实现的是验证以下列的内容以匹配下拉列表中新选择的类型。如果不匹配,我希望在网格上显示验证错误。我使用 INotifyDataErrorInfo 接口实现了我的验证,它工作得非常好,除非我在后面的代码中使用它。当后面的代码调用验证时,数据网格的 ValidationSummary 永远不会更新。我在这里做错了什么???使用调试器时,我可以清楚地看到错误被添加到接口的错误字典中......

这是处理程序:

        private void TypeBoxChanged(object sender, EventArgs e)
        {
        ComboBox box = (sender as ComboBox);
        IncomingPolicy row = (IncomingPolicy)box.DataContext;

        string ruleTypeValue = TypeList.GetKeyForText(box.SelectedItem.ToString());
        //check if the type is the same
        if(row.TypeWrapper == ruleTypeValue)
            return;
        if (row.ValidateRule(ruleTypeValue))
        {
            //SAVE the record
        }
        else
        {
            row.RaiseErrorsChanged("RuleWrapper");
        }
    }

验证规则方法将根据规则类型值调用此方法

        public bool ValidateRegularExpression(string property, string value, string expression, string errorMessage)
        {
        bool isValid = true;
        Regex regex = new Regex(expression);
        Match match = regex.Match(value);
        if (match.Success)
        {
            RemoveError(property, errorMessage);                
        }
        else
        {
            AddError(property, errorMessage, false);
            isValid = false;
        }

        return isValid;
    }

我遵循了 MSDN http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifydataerrorinfo%28VS.95%29.aspx上的示例实现

4

1 回答 1

4

早些时候,我实现了验证助手并为接口IDataErrorInfo和创建了示例解决方案INotifyDataErrorInfo

http://vortexwolf.wordpress.com/2011/10/01/wpf-validation-with-idataerrorinfo/

源代码

主要实现在这里:

this.PropertyChanged += (s, e) => 
{
    // if the changed property is one of the properties which require validation
    if (this._validator.PropertyNames.Contains(e.PropertyName))
    {
        this._validator.ValidateProperty(e.PropertyName);
        OnErrorsChanged(e.PropertyName);
    }
}

无论验证是否成功,您都应该始终调用OnErrorsChanged(或RaiseErrorsChanged在您的情况下)方法:如果属性无效 - 将显示红色边框,如果有效 - 绑定控件将返回到其正常状态。

于 2012-03-13T12:46:21.467 回答