开发者

Validation of WPF User Input using MVVM and Entity Framework 4.0

开发者 https://www.devze.com 2022-12-31 09:47 出处:网络
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.

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.


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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消