3

I am building a WPF 4.0 Application using MVVM. The Model is generated using Entity Framework 4.0. I am using Data binding on the WPF to bind the user input to model properties.

What is the easiest way to validate user input ? I prefer an approach where I can set the validation rules on the Model rather than on the WPF itself. How can this be done? Any samples are appreciated.

2 Answers 2

1

The easiest way i found is taken from this book, pages 624-625.

The ViewModel should implement IDataErrorInfo

private string _newItem;

public string NewItem
        {
            get { return _newItem; }
            set
            {
                if (Equals(_newItem, value)) return;
                _newItem = value;
                SendPropertyChanged("NewItem");
            }
        }

public string this[string propertyName]
        {
            get
            {
                if (propertyName == "NewItem")
                {
                    var valid = NewItem.All(Char.IsLetterOrDigit);
                    if (!valid)
                        return "NewItem can only contain letters and numbers.";
                }
                return null; 
            }
        }

And the view the long version:

<TextBox>
   <TextBox.Text>
      <Binding UpdateSourceTrigger="PropertyChanged" Path="NewItem">
         <Binding.ValidationRules>
            <DataErrorValidationRule></DataErrorValidationRule>
         </Binding.ValidationRules>
      </Binding>
   </TextBox.Text>
</TextBox>

Or the short version:

<TextBox Text="{Binding NewItem,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"/>

It should create a nice red border around your textbox when rule fails, and you can play around with the error message the way you want, for example bind the error message to a textbox tool tip (MSDN):

<Window.Resources>
        <Style x:Key="TextBoxInError" TargetType="TextBox">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip"
              Value="{Binding RelativeSource={x:Static RelativeSource.Self},
              Path=(Validation.Errors)[0].ErrorContent}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>

And then just add this to the textbox:

Style="{StaticResource TextBoxInError}"

Cheers!

Sign up to request clarification or add additional context in comments.

Comments

0

The BookLibrary sample application of the WPF Application Framework (WAF) project shows a MVVM application. It uses the Entity Framework and defines the validation rules on the Model (Entity) classes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.