【问题标题】:INotifyDataErrorInfo not raising error changed in code behindINotifyDataErrorInfo 未在后面的代码中引发错误
【发布时间】:2012-03-13 20:46:21
【问题描述】:

我遇到了从代码隐藏执行验证的问题。我的数据显示在数据网格中。其中一列(类型)是下拉菜单,当下拉菜单发生更改时,它会触发 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

【问题讨论】:

  • 我认为无论验证是否成功,您都应该始终调用 RemoveError。或者尝试将对 RaiseErrorsChanged(property) 的调用添加到方法的末尾。
  • 如果问题仅与 ValidationSummary 控件有关(而不是红色边框),请尝试将 NotifyOnValidationError=True 添加到应该验证的绑定中。
  • @vorrtex 我错过了 RaiseErrorChanged 如果你把它作为答案,我会标记它。谢谢

标签: c# silverlight validation inotifydataerrorinfo


【解决方案1】:

前段时间,我实现了验证助手并为IDataErrorInfoINotifyDataErrorInfo 两个接口创建了示例解决方案:

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

Source code

主要实现在这里:

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)方法:如果属性无效 - 将显示红色边框,如果有效 - 绑定控件将恢复正常。

【讨论】:

  • 我正在尝试您的代码。试图用 MVVM 来实现它。希望它运作良好。感谢您的开始。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-26
  • 1970-01-01
  • 2011-09-28
  • 2017-04-05
  • 1970-01-01
  • 1970-01-01
  • 2017-02-12
相关资源
最近更新 更多