代码之家  ›  专栏  ›  技术社区  ›  Dave Barker

WPF绑定-如何确定对象无效以防止保存

  •  6
  • Dave Barker  · 技术社区  · 16 年前

    我在WPF应用程序中有一个文本框绑定到实现IDataErrorInfo的Linq to Entities类的属性。文本框绑定的validateNextExceptions=true和validatesOndataerrors=true。当文本框绑定到整数属性并且用户输入文本时,文本框轮廓显示为红色,因为我没有设置自定义样式。

    在我的保存方法中,我如何知道对象无效,无法保存?我希望用户单击“保存”按钮,我可以将问题通知他们,而不是禁用“保存”按钮。

    干杯,

    戴夫

    2 回复  |  直到 16 年前
        1
  •  5
  •   Matt Hamilton    16 年前

    我还没有找到一个简单的方法。我在陷阱周围找到了一些代码,可以在表单上的所有控件中循环使用,并确定其中是否有验证错误。最后我把它变成了一种扩展方法:

    // Validate all dependency objects in a window
    internal static IList<ValidationError> GetErrors(this DependencyObject node)
    {
        // Check if dependency object was passed
        if (node != null)
        {
            // Check if dependency object is valid.
            // NOTE: Validation.GetHasError works for controls that have validation rules attached 
            bool isValid = !Validation.GetHasError(node);
            if (!isValid)
            {
                // If the dependency object is invalid, and it can receive the focus,
                // set the focus
                if (node is IInputElement) Keyboard.Focus((IInputElement)node);
                return Validation.GetErrors(node);
            }
        }
    
        // If this dependency object is valid, check all child dependency objects
        foreach (object subnode in LogicalTreeHelper.GetChildren(node))
        {
            if (subnode is DependencyObject)
            {
                // If a child dependency object is invalid, return false immediately,
                // otherwise keep checking
                var errors = GetErrors((DependencyObject)subnode);
                if (errors.Count > 0) return errors;
            }
        }
    
        // All dependency objects are valid
        return new ValidationError[0];
    }
    

    因此,当用户单击表单上的“保存”按钮时,我会执行以下操作:

    var errors = this.GetErrors();
    if (errors.Count > 0)
    {
        MessageBox.Show(errors[0].ErrorContent.ToString());
        return;
    }
    

    这比它应该做的工作要多得多,但是使用扩展方法可以简化一点。

        2
  •  3
  •   Robert Macnee    16 年前

    你可以设定 NotifyOnValidationError true 对你 Binding s,然后为 Error 某些父元素上的事件。每当添加或删除错误时,将触发事件。