Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reset on error #39

Open
JohanLarsson opened this issue Nov 11, 2016 · 0 comments
Open

reset on error #39

JohanLarsson opened this issue Nov 11, 2016 · 0 comments

Comments

@JohanLarsson
Copy link
Member

    public class ValueControl : Control
    {
        public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
            "Value",
            typeof(int),
            typeof(ValueControl),
            new FrameworkPropertyMetadata(
                default(int),
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                null,
                CoerceValue));

        private bool isResetting;

        static ValueControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(ValueControl), new FrameworkPropertyMetadata(typeof(ValueControl)));
            EventManager.RegisterClassHandler(typeof(ValueControl), Validation.ErrorEvent, new EventHandler<ValidationErrorEventArgs>(OnError));
        }

        public int Value
        {
            get { return (int)this.GetValue(ValueProperty); }
            set { this.SetValue(ValueProperty, value); }
        }

        private static object CoerceValue(DependencyObject d, object basevalue)
        {
            var control = (ValueControl)d;
            if (control.isResetting)
            {
                return control.GetValue(ValueProperty);
            }

            return basevalue;
        }

        private static void OnError(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
            {
                var control = (ValueControl)sender;
                control.isResetting = true;
                BindingOperations.GetBindingExpressionBase(control, ValueProperty)?.UpdateTarget();
                control.isResetting = false;
            }
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant