Gorgsenegger
Gorgsenegger

Reputation: 7856

Can I combine different settings for UpdateSourceTrigger in WPF (MVVM) for a TextBox control?

I have an MVVM application with a TextBox control for which I want to validate that it's not empty. As the evaluation should be performed for every key stroke, I changed the binding so it contains

Text={Binding ..., UpdateSourceTrigger=PropertyChanged}

Now I'd also like to perform an action when the TextBox control loses its focus, so the default behaviour of the TextBox control would be suitable. My problem is that I don't know how to combine the two settings (if at all possible).

Any idea? How to react to key strokes and to the LostFocus event?

Upvotes: 0

Views: 1130

Answers (3)

eandersson
eandersson

Reputation: 26362

You would normally implement IDataErrorInfo or INotifyDataErrorInfo interfaces into your ViewModels to handle this in MVVM.

Also, attributes are really powerful and could probably provide you with a good solution, depending on the requirements you have. It would look something like this in your ViewModel.

[Required(ErrorMessage = "Field 'Range' is required.")]
[Range(1, 10, ErrorMessage = "Field 'Range' is out of range.")]
public int Range
{
    get
    {
        return this.range;
    }
    set
    {
        if (this.range != value)
        {
            this.range = value;
            this.OnPropertyChanged("Range");
        }
    }
}

enter image description here

I would recommend that you take a look at these articles.

Attributes-based Validation in a WPF MVVM Application http://www.codeproject.com/Articles/97564/Attributes-based-Validation-in-a-WPF-MVVM-Applicat

Validating User Input - WPF MVVM http://www.codeproject.com/Articles/98681/Validating-User-Input-WPF-MVVM

WPF Validation with Attributes and IDataErrorInfo interface in MVVM http://weblogs.asp.net/marianor/archive/2009/04/17/wpf-validation-with-attributes-and-idataerrorinfo-interface-in-mvvm.aspx

Using IDataErrorInfo for validation in MVVM with Silverlight and WPF http://www.arrangeactassert.com/using-idataerrorinfo-for-validation-in-mvvm-with-silverlight-and-wpf/

Upvotes: 1

awsomedevsigner
awsomedevsigner

Reputation: 150

You should consider using the IDataErrorInfo interface and the ValidatesOnErrorInfo property for your binding. A good and simple blog-post on how to use these two can be found here: http://asimsajjad.blogspot.de/2010/08/input-validation-using-mvvm-pattern.html

Upvotes: 1

Thomas Levesque
Thomas Levesque

Reputation: 292735

You can use an attached behavior to map the LostFocus event to a command in your ViewModel.

Upvotes: 2

Related Questions