views:

478

answers:

3

Does it make sense that if the Text on a TextBox is databound to a property using the twoway mode and I set the Text to something, it should update the property? My property gets updated when I type inside the control, but not when I set the value in code.

+1  A: 

I would say it makes no sense to modify a bound Text property directly. Your code should be setting the other end of the binding and allowing the binding to update the control.

If the bound object is updated when the Text property is set then special case code would be needed to detect when such an assignent is the result of the bound object changing for other reasons. Otherwise you would end up with an infinite loop.

AnthonyWJones
The question comes from some work I'm doing with adding/removing databindings programatically. I'm finding that whenever I set a binding in code, it sets the property I'm bounding to and the textbox to empty strings. When I set the databinding again, I want the text inside the textbox to be set to the property and not the other way around. Why I am removing the databinding in the first place? Because the property gets continously updated and I don't want the textbox to change its text when its in focus.
Steve the Plant
Perhaps you should include these details perhaps with a little code in the question itself.
AnthonyWJones
A: 

This is because it only commits the data when the textbox loses focus. Here is a question that is somewhat related that eludes to this.

joshlrogers
A: 

You shouldn't set the .Text value of the textbox... set the value of the property it's binding to. :)

I'd encourage you to read more about the Model-View-ViewModel method for designing your views. It keeps a clear separation of concerns when doing this kind of work. The reason you are seeing this "bug" regarding focus causing the binding to refresh is because most of the time this kind of thing is not appropriate.

Here's a pretty good video introduction to MVVM: MVVM on Channel 9

Anderson Imes