CRM Development

Solutionist has designed the architecture for a new CRM system for use in the medical imaging industry.

Thursday, 2 February 2012

How to get a WPF TextBox to update its ViewModel binding variable

A short post:

Scenario:
You're using MVVM and have bound a textbox to a string ViewModel property - in TwoWay mode.

You have a button that is only to be enabled when that string property is not null/empty. 

Problem: 
You type in the textbox, but the button remains firmly disabled until the textbox loses focus.
Only at that point is the string's PropertyChanged event raised.

Solution:
(Taken from  http://betaforums.silverlight.net/forums/t/103695.aspx )
Do the following on the TextBox's TextChanged event:
      void summaryTextBox_TextChanged(object sender, TextChangedEventArgs e)
      {
          TextBox txCtl = (TextBox)sender;
          if (txCtl != null)
          {
              var be = txCtl.GetBindingExpression(TextBox.TextProperty);
              if (be != null)
              {
                  be.UpdateSource();
              }
          }
       }
This will force the PropertyChanged event to be raised whenever the text is changed - and your button will be enabled as soon as you start typing in the TextBox.

No comments:

Post a Comment