WPF user login validation using MVVM and Entity Framework 4.0

I am creating a WPF 4.0 application using MVVM. The model is built using Entity Framework 4.0. I am using WPF data binding to bind user input to model properties.

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

+2


a source to share


2 answers


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



0


a source


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

ViewModel must 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 kind of 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}"/>

      

When breaking the rule, it should create a nice red border around your text box and you can play around with the error message the way you want, for example linking the error message to a text editor tooltip ( 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}"

      

Hooray!

0


a source







All Articles