【问题标题】:C# WPF MVVM TextBox value doesn't changeC# WPF MVVM TextBox 值不会改变
【发布时间】:2011-08-11 08:44:28
【问题描述】:

我是在 WPF 中使用 MVVM 的初学者,发现似乎无法更改文本框或标签的值。这是一个例子。

在 Xaml 中:

Name 的原始值为“Peter”。

但是在我按下一个在 ViewModel 中调用命令并将 Name 的值更改为的按钮之后 “约翰”。因此,假设文本框的值也将更改为 John。但是,它不会改变。

我在网上找了很多例子,发现没有一个实现这种功能。我从他们那里学到的是使用 ListView 的 Command 和 ItemsSource。 当我使用 button to raise 命令更改视图的 ItemsSource 时,ListView 的值会发生变化。当 Binding to ItemsSource 改变时,它的值会自动改变。

但是,即使绑定到它们的值已经更改,我也无法更改 TextBox 或 Label 的值。

实际上,我在 MVVM 方面真的很年轻。我想我还有很多我不知道的。 你能给我一个例子,说明我应该如何在单击按钮后对文本框进行更改?顺便说一句,我不太确定如何为按钮制作命令。它似乎涉及我在网上的示例中找到的很多代码。有没有更简单的方法?

非常感谢。

【问题讨论】:

  • 你的 ViewModel 是否实现了INotifyPropertyChanged
  • +1 Stephan 我建议你把它写下来,因为它可能就是答案。
  • 非常感谢!我真的没有这样做。
  • 但是怎么做呢?我在网上没有找到任何东西。再次感谢!
  • 我同意斯蒂芬的观点,但是你能把你的模型代码放在这里吗?

标签: c# wpf mvvm textbox


【解决方案1】:

您的 ViewModel 需要实现 INotifyPropertyChanged 。 文档见here

public class Bar : INotifyPropertyChanged
{
  public event PropertyChangedEventHandler PropertyChanged;
  private string foo;
  public string Foo 
  {
    get { return this.foo; }
    set 
    { 
      if(value==this.foo) 
        return;
      this.foo = value;
      this.OnPropertyChanged("Foo");
    }
  }
  private void OnPropertyChanged(string propertyName)
  {
    if(this.PropertyChanged!=null)
      this.PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
  }  
}

【讨论】:

  • 大家好,我已经包含了命名空间 System.ComponentModel,但是关键字 PropertyChanged 仍然是黑色的。为什么?
  • ProertyChanged 是在INotifyPropertyChanged 中定义的事件的名称。您需要实现该接口。我更新了答案并添加了事件声明。
  • 我是否必须向 PropertyChanged 添加任何内容??
  • Bar代表你的ViewModel,属性Foo代表你ViewModel的属性Name
【解决方案2】:

您的视图模型应该实现INotifyPropertyChanged,以便 WPF 知道您已经更改了属性的值。

这是一个来自

的例子
// This is a simple customer class that 
// implements the IPropertyChange interface.
public class DemoCustomer  : INotifyPropertyChanged
{
    // These fields hold the values for the public properties.
    private string customerNameValue = String.Empty;

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(String info)
    {
        var listeners = PropertyChanged;
        if (listeners  != null) 
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }

    public string CustomerName
    {
        get
        {
            return this.customerNameValue;
        }

        set
        {
            if (value != this.customerNameValue)
            {
                this.customerNameValue = value;
                NotifyPropertyChanged("CustomerName");
            }
        }
    }
}

【讨论】:

  • 将此代码添加到 ViewModel?我必须向 PropertyChanged 添加任何内容吗?还需要做些什么才能使其正常工作吗?
猜你喜欢
  • 2011-03-04
  • 2016-05-07
  • 2019-09-06
  • 2011-04-13
  • 1970-01-01
  • 2022-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多