代码之家  ›  专栏  ›  技术社区  ›  A Coder

绑定在ViewModel命令方法MVVM中不起作用

  •  -2
  • A Coder  · 技术社区  · 7 年前

    我在做一件事 MVVM WPF 从中绑定多个值的应用程序 ViewModel 查看。

    现在我创造了一个新的 视图模型 TextBox 过了一段时间 Button

    我很困惑。

    视图模型:

    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 回复  |  直到 7 年前
        1
  •  1
  •   Sancho Panza    7 年前

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

    视图的初始绑定(读取值)发生在调用ViewModel构造函数并设置值之后

        2
  •  0
  •   Coops    7 年前

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

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

    INotifyPropertyChanged Interface

    How to: Implement the INotifyPropertyChanged Interface