Mark Pearl
Mark Pearl

Reputation: 7673

Change a textbox bound text value in the set accessor

I hope someone can help me with this one, I suspect I am doing something stupid. I have bound a TextBox so that the Text is bound to InputValue. Basically, when the text value changes I have a method (Inches.Parse), which examines the value and returns a well formatted string.

If there are no errors with the parsing I want the textbox to have the well formatted string called "result". However, the TextBox won't show the new text? Any help would be appreciated.

public string InputValue 
{
    get
    {
        return _inputValue;
    }
    set
    {
        if (_inputValue != value)
        {                                        
            bool error;
            string result = Inches.Parse(value, 64, out error);                    

            if (error != IsValid)
            {
                IsValid = error;
            }
            if (!error)
            {
                _inputValue = result;
            }
            else
            {
                _inputValue = value;
            }

            NotifyPropertyChanged("InputValue");
        }
    }
}

Upvotes: 1

Views: 383

Answers (2)

dh.
dh.

Reputation: 1511

The problem seems to be that the TextBox will not update the presented value during updating of the source property it is bound to by itself.

The workaround could be to set this binding expression

{Binding Path=InputValue, Mode=TwoWay,UpdateSourceTrigger=Explicit}

note the UpdateSourceTrigger=Explicit this says that you will update the source manually

then you add handler to TextBox LostFocus event (so we are sure user has finished editing)

textBox1.LostFocus +=
(s, e) =>
  {
    var text = textBox1.Text;
    [DataSource].InputValue = text;
  };

So when TextBox loses focus the value in the datasource will be updated and formatted and then the TextBox will be rebound.

Hope this will help you.

Upvotes: 1

Aran Mulholland
Aran Mulholland

Reputation: 23935

This is a bug/issue that will apparently be fixed in dot net 4.0

Basically the problem is that if a binding sets a property it does not look for NotifyPropertyChanged during the setter. you can workaround this issue, by calling NotifyPropertyChanged on the main ui thread with a dispatcher. it is done like this

Application.Current.Dispatcher.BeginInvoke((Action)delegate { NotifyPropertyChanged("InputValue"); });

put this in your setter and you should be fine..

Upvotes: 3

Related Questions