Use LogicalTreeHelper to Validation

来源:互联网 发布:淘宝售前客服岗位职责 编辑:程序博客网 时间:2024/06/05 03:26
 public class Validator    {        // Validate all dependency objects in a window        public static bool IsValid(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 false;                }            }            // 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                    if (IsValid((DependencyObject) subnode) == false) return false;                }            }            // All dependency objects are valid            return true;        }    }

private void BtnSave_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)        {            if (Validator.IsValid(this))            {                e.Handled = false;            }            else            {                e.Handled = true;            }        }        private void UserControl_PreviewKeyDown(object sender, KeyEventArgs e)        {            if (e.Key == Key.Enter)            {                if (Validator.IsValid(this))                {                    e.Handled = false;                }                else                {                    e.Handled = true;                }            }        }

0 0
原创粉丝点击