绑定在ViewModel命令方法MVVM

时间:2018-10-30 10:50:54

标签: c# wpf mvvm

我正在开发一个MVVM WPF应用程序,其中将多个值从ViewModel绑定到View。

现在,我创建了一个新的ViewModel,在其中单击TextBox后必须将值绑定到Button。当我尝试这种简单的绑定时,它对我不起作用。令我惊讶的是,在构造函数中分配值时,绑定有效。

我很困惑。

ViewModel:

public ABCViewModel{
       txtItems = "Hello world";      //this works
}


 private string m_stxtItem = "";

        public string txtItems
        {
            get { return this.m_stxtItem; }

            set
            {
                if (this.m_stxtItem != value)
                {                    
                    this.m_stxtItem = value;

                }
            }
        }

public ICommand BindTextValue { get { return new RelayCommand(SeriesBinding); } }

 private void SeriesBinding()
        {
               txtItems = "Hi";                         //does not work

        }

XAML:

<TextBox Text="{Binding txtItems,Source={StaticResource ABCViewModel}}" />

<Button Command="{Binding BindTextValue,Source={StaticResource ABCViewModel}}">Click</Button>

为什么这不起作用,我在哪里错了?

2 个答案:

答案 0 :(得分:1)

简单的回答:您缺少自动数据绑定所需的INotifyPropertyChanged实现。

关于在构造函数中设置值时为何起作用的扩展答案: 从视图中进行初始绑定(读取值)发生在调用ViewModel-constructor并设置了值之后

答案 1 :(得分:0)

您需要在ViewModel上实现INotifyPropertyChanged接口。

以下是有关接口的含义以及如何实现的一些MSDN链接:

INotifyPropertyChanged Interface

How to: Implement the INotifyPropertyChanged Interface

基本上是因为您已将ViewModel设置为View的数据源,所以在构造时,View会向ViewModel查找其值。从这一点开始,ViewModel需要某种机制来通知视图更改。视图不会定期更新或类似的更新。这是INotifyPropertyChanged接口所处的位置。WPF框架会寻找这些被触发的事件,并使View刷新其值。

相关问题