简体   繁体   English

TextBox.Text绑定到ViewModel的属性

[英]TextBox.Text binding to a ViewModel's property

I have a problem with two way binding a TextBox content to a property in another class. 我有两种方式将TextBox内容绑定到另一个类中的属性时遇到问题。 Searching stackoverflow gave a lot of tips/solutions but none seem to work. 搜索stackoverflow提供了很多技巧/解决方案,但似乎都没有用。

In my XAML code I have: 在我的XAML代码中,我有:

< TextBox ... Width="336" IsReadOnly="True"
 Text="{Binding Path=AssignedClearProgram, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>

(... I removed all non important items) (...我删除了所有不重要的内容)

In the accompanies cs code I have: 在随附的CS代码中,我有:

public CombiWindow(Combi combi)
{
    ViewModel = new CombiViewModel(combi);
    DataContext = ViewModel;
}

In the CombiViewModel: 在CombiViewModel中:

    [UsedImplicitly]
    public string AssignedClearProgram { get; set; }

It seems that the first time I assign AssignedClearProgram, the textbox is filled with the text that I set, however after the window is displayed and AssignedClearProgram gets updated from the code (ie the set method is called), the data is not updated in the screen. 似乎我第一次分配AssignedClearProgram时,文本框中填充了我设置的文本,但是在显示窗口并从代码中更新AssignedClearProgram之后(即调用set方法),该数据不会在屏幕。

Does anybody have a solution to update the textbox when this variable is changed? 更改此变量后,是否有人有解决方案来更新文本框?

Kind regards, 亲切的问候,

Michel 米歇尔

Your viewmodel class needs to implement INotifyPropertyChanged and you need to raise that interface's event whenever you change the property. 您的viewmodel类需要实现INotifyPropertyChanged,并且每当更改属性时,都需要引发该接口的事件。 Then the binding will spot changes and update the textbox. 然后绑定将发现更改并更新文本框。

Your view model class should implement the INotifyPropertyChanged interface. 您的视图模型类应实现INotifyPropertyChanged接口。

Your property would then look like the following: 这样,您的媒体资源将如下所示:

private string assignedClearProgram;

public string AssignedClearProgram
{
   get { return assignedClearProgram; }
   set
   {
       if (assignedClearProgram != value)
       {
           assignedClearProgram = value;

           // Notify property has changed here using PropertyChanged event from INotifyPropertyChanged.
       }
   }
}

Read this article for an example of how to implement the INotifyPropertyChanged interface and utilize its PropertyChanged event. 阅读文章为如何实现的一个例子INotifyPropertyChanged接口,并利用它PropertyChanged事件。

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

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