简体   繁体   English

WPF文本框未从视图模型更新

[英]Wpf text box not updated from view model

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". 因此属性Text alwasys返回“测试”。

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. 现在,当我在文本框中键入内容时,将调用setter,它会调用PropertyChanged。

After this something ( probably the GUI ) calls the getter and gets the value "testing". 之后,某些东西(可能是GUI)调用getter并获得值“ 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". 因此,我可以在文本框中键入“ abc”,并且即使模型只是存储“ testing”,文本框也会显示“ abc”。

why isnt the text in the text box not reset to "testing" at each keystroke? 为什么每次击键时文本框中的文本都不会重置为“测试”?

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. 删除设置器,使绑定成为一种方式,在更改常量时提高text属性,并使文本框为只读。 Remember, its not necessary to call Propertychanged in the setter. 请记住,不必在设置器中调用Propertychanged。

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. 我想补充一点,这是一个非常糟糕的主意,并强烈建议您不要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM