[英]C# WPF MVVM TextBox value doesn't change
我是在 WPF 中使用 MVVM 的初学者,发现似乎无法更改文本框或 label 的值。 这是一个例子。
在 Xaml 中:
Name 的原始值为“Peter”。
但是在我按下一个在 ViewModel 中调用命令并将 Name 的值更改为“John”的按钮之后。 因此,假设文本框的值也将更改为 John。 但是,它没有改变。
我在网上找到了很多例子,发现没有一个实现了这种功能。 我从他们那里学到的是使用 ListView 的 Command 和 ItemsSource。 当我使用 button to raise 命令更改视图的 ItemsSource 时,ListView 的值会发生变化。 当 Binding to ItemsSource 改变时,它的值会自动改变。
但是,即使绑定到它们的值已经更改,我也无法更改 TextBox 或 Label 的值。
实际上,我在 MVVM 方面真的很年轻。 我想我还有很多我不知道的。 你能给我一个例子,说明我应该如何在单击按钮后对文本框进行更改? 顺便说一句,我不太确定如何为按钮制作命令。 它似乎涉及我在网上的示例中找到的很多代码。 有没有更简单的方法?
非常感谢。
您的 ViewModel 需要实现INotifyPropertyChanged
。 文档见这里
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));
}
}
您的视图 model 应该实现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");
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.