Validating a WPF Form Before the Initial Update Using IDataErrorInfo

I am trying to implement elegant form validation in a C # / WPF / Entity Framework 4.0 application. I have a classic form (some text fields and checkboxes) and a save button.
I want to update the source code (and database) when the user clicks on save, and I also only want to run form validation when the user clicks on save.

I set all my bindings with parameter UpdateSourceTrigger=Explicit. I also posted all the bindings to BindingGroup.

When the user clicks save, I start the UpdateSourcesbinding group method - this calls UpdateSourcefor each binding. At this stage ( until the source code is updated ), I want the form to be validated and the errors highlighted in the graphical interface. If there are no input errors, the update should be free.

I thought that I could achieve this by doing IDataErrorInfoin EntityObjectwhich the fields are bound and setting the parameter ValidatesOnDataErrors=Trueto all my bindings.

Unfortunately, this does not work because, as explained here: MSDN Binding Overview - Validating Data Under the Heading “Validation Process”

5) The binding mechanism sets the source property.

6)...... , , ValidatesOnDataErrors, true.

- , "" ? ... - - ?

, :
, , ?

+5
1

, IDataErrorInfo Name . ( ) , .

, , , , , , .

, .

:

IProposedValueErrorInfo.cs

using System.Globalization;

namespace WpfApplication
{
    public interface IProposedValueErrorInfo
    {
        object GetError(string propertyName, object value, CultureInfo cultureInfo);
    }
}

ProposedValueErrorValidationRule.cs

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace WpfApplication
{
    internal sealed class ProposedValueErrorValidationRule : ValidationRule
    {
        private readonly DependencyObject targetObject;
        private readonly DependencyProperty targetProperty;

        public ProposedValueErrorValidationRule(DependencyObject targetObject, DependencyProperty targetProperty)
            : base(ValidationStep.RawProposedValue, true)
        {
            if (targetObject == null)
                throw new ArgumentNullException("targetObject");
            if (targetProperty == null)
                throw new ArgumentNullException("targetProperty");

            this.targetObject = targetObject;
            this.targetProperty = targetProperty;
        }

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var expression = BindingOperations.GetBindingExpression(this.targetObject, this.targetProperty);
            if (expression != null)
            {
                var sourceItem = expression.DataItem as IProposedValueErrorInfo;
                if (sourceItem != null)
                {
                    var propertyName = expression.ParentBinding.Path != null ? expression.ParentBinding.Path.Path : null;
                    if (propertyName != null)
                    {
                        var error = sourceItem.GetError(propertyName, value, cultureInfo);
                        if (error != null)
                            return new ValidationResult(false, error);
                    }
                }
            }
            return ValidationResult.ValidResult;
        }
    }
}

ProposedValueValidationBindingExtension.cs

using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;

namespace WpfApplication
{
    public sealed class ProposedValueValidationBindingExtension : MarkupExtension
    {
        private readonly Binding binding;

        public ProposedValueValidationBindingExtension(Binding binding)
        {
            if (binding == null)
                throw new ArgumentNullException("binding");

            this.binding = binding;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            var provideValueTarget = serviceProvider != null ? serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget : null;
            if (provideValueTarget != null)
                this.binding.ValidationRules.Add(new ProposedValueErrorValidationRule(provideValueTarget.TargetObject as DependencyObject, provideValueTarget.TargetProperty as DependencyProperty));

            return this.binding.ProvideValue(serviceProvider);
        }
    }
}

Person.cs

using System.Globalization;

namespace WpfApplication
{
    public class Person : IProposedValueErrorInfo
    {
        public int Age { get; set; }
        public string Surname { get; set; }

        #region IProposedValueErrorInfo Members

        object IProposedValueErrorInfo.GetError(string propertyName, object value, CultureInfo cultureInfo)
        {
            switch (propertyName)
            {
                case "Age":
                    int dummy;
                    return value is int || int.TryParse(value as string, NumberStyles.Integer, cultureInfo, out dummy) ? null : "Age must be a number.";
            }

            return null;
        }

        #endregion
    }
}

MainWindow.xaml

<Window x:Class="WpfApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:Person Age="16"/>
    </Window.DataContext>
    <StackPanel>
        <TextBox Text="{local:ProposedValueValidationBinding {Binding Age}}" ToolTip="{Binding Path='(Validation.Errors)/ErrorContent', RelativeSource={RelativeSource Self}}"/>
        <TextBox Text="{local:ProposedValueValidationBinding {Binding Age}}" ToolTip="{Binding Path='(Validation.Errors)/ErrorContent', RelativeSource={RelativeSource Self}}"/>
    </StackPanel>
</Window>
+1

All Articles