问题
I have a property in my view model which returns a constant under some conditions.
which is implemented similiar to this:
class Tmp : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public String Text
{
get { return "testing"; }
set
{
PropertyChanged(this,new PropertyChangedEventArgs("Text")); }
}
}
so the property Text alwasys returns "testing".
I bound this to a text box like :
<TextBox Text="{Binding Path=Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
When the application starts, the textbox correclty says testing.
now when I type something in the text box the setter gets called, which calls PropertyChanged.
After this something ( probably the GUI ) calls the getter and gets the value "testing".
However the text in the textbox is not changed back to testing.
So I can type "abc" into the text box, and text box displays "abc" even though the model is just storing "testing".
why isnt the text in the text box not reset to "testing" at each keystroke?
回答1:
Why should the textbox get the text again? It just wrote it into your source property it "knows" that it must be the same, because he is in the middle of telling the property the new value. Otherwise you would create circular references. What you are doing is going completely against guidelines and behavior expected from a property.
Remove the setter, make the binding one way, raise the text property when your constant is changed, and make the textbox readonly. Remember, its not necessary to call Propertychanged in the setter.
To make your initial approach work, you need to break out of the "Textbox changes property but won't listen for incoming raises" state
set
{
sUIDispatcher.BeginInvoke((Action)(() => Raise("Name")));
}
i would like to add, that this is a REALLY bad idea and strongly discourage you to do it like that.
来源:https://stackoverflow.com/questions/11054510/wpf-text-box-not-updated-from-view-model