WPF TextBox MVVM DataBinding & use of UpdateSourceTrigger

If you are using a TextBox in your WPF application with MVVM pattern & want to keep the TextBox Text and the property in the ViewModel synchronized, you need to use UpdateSourceTrigger=PropertyChanged in the binding. Here is an example:

View XAML:
<Window x:Class="WPF.MainWindow" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        Title="WPF TextBox MVVM DataBinding Example" Height="500" Width="500">
    <Grid>
        <TextBox Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Height="25" />
    Grid>
Window>

View Code Behind:
using WPF.ViewModel;

namespace WPF
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new TextBoxViewModel();
        }
    }
}

ViewModel:
using System.ComponentModel;

namespace WPF.ViewModel
{
    public class TextBoxViewModel : INotifyPropertyChanged
    {
        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged("Name");
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;


        public void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(thisnew PropertyChangedEventArgs(propertyName));
        }

        #endregion INotifyPropertyChanged Members
    }
} 


  

Comments

  1. Hi,
    I'm doing the same way for binding,
    with a little difference,
    I want to check if the enter (\r\n) pressed or not, then do something and clear the textbox.
    so I changed the 'set' to:

    {
    _name = value;
    if (_name.IndexOf("\r\n") > -1)
    {
    dosomething();
    _name = "";
    }
    OnPropertyChanged("Name");
    }

    this works if I enter some text and then press enter,
    but if I press enter, the "\r\n" value remains in the textbox !
    any idea?

    ReplyDelete

Post a Comment

Popular posts from this blog

WPF How to Dispose ViewModel when the associated UserControl (Not Window) closes?

C# How to unit test Dispatcher

WPF: How to Deep Copy WPF object (e.g. UIElement) ?