WPF绑定不更新视图
我有一个文本块:
... Status ...
代码隐藏:
public StatusPage() { InitializeComponent(); this.DataContext = new StatusPageViewModel(this); }
并在viewModel中:
private string _statusText; /// /// Status text /// public string StatusText { get { return _statusText; } set { _statusText = value; } }
并在viewModel中的函数:
string statusText = Status.GetStatusText(); this.StatusText = statusText;
GetStatusText()
返回类似“Work done”等的字符串。来自该函数的值被赋予this.StatusText,但TextBlock的text属性不会改变,并且仍显示占位符“… Status …”
我知道这样的问题 – > 点击 <—但是看完之后我仍然无法找到解决方案
@Update
根据你的建议我更新了我的代码,现在我有了这个:
public string StatusText { get { return _statusText; } set { _statusText = value; RaisePropertyChanged("StatusText"); } }
和viewModel的声明:
public class StatusPageViewModel : ObservableObject, INavigable
哪里:
ObservableObject类是:
public abstract class ObservableObject : INotifyPropertyChanged { #region INotifyPropertyChanged Members /// /// Raises the PropertyChange event for the property specified /// /// Property name to update. Is case-sensitive. public virtual void RaisePropertyChanged(string propertyName) { OnPropertyChanged(propertyName); } /// /// Raised when a property on this object has a new value. /// public event PropertyChangedEventHandler PropertyChanged; /// /// Raises this object's PropertyChanged event. /// /// The property that has a new value. protected virtual void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) { var e = new PropertyChangedEventArgs(propertyName); handler(this, e); } } #endregion // INotifyPropertyChanged Members }
但它仍然无法正常工作
您需要在ViewModel顺序中实现INotifyPropertyChanged
,以通知View属性已更改。
这是MSDN页面的链接: System.ComponentModel.INotifyPropertyChanged
最重要的是要在属性设置器中引发PropertyChanged
事件。
两种方式添加绑定模式,因为默认情况下Textblock的绑定模式是一种方式
... Status ...
当然,您需要为此目的实现INotifyPropertyChanged ,请参阅此链接以了解如何实现。
您的视图模型需要实现INotifyPropertyChanged
,并且每次您的某个属性更改时(即在setter中)都需要提高它。
没有它,WPF无法知道该属性已经发生变化。
使用DataModels时,您必须确保模型在初始加载时完成。 所以,如果你这样做:this.DataContext = mainViewModel和你的mainViewModel的某些部分没有加载(= null),那么你无法绑定它们。 例如,我在该模型中有一个Model对象程序。 我将TextBlock的Text绑定到Model.Program.Name。 Program对象在初始加载时未连接,因此您必须重新绑定到已加载的对象,否则无法发送通知。
我有这个问题,这就是我做错了……
注意:我有正确的INotifyPropertyChanged编码。
在我看来,我有
…这会调用VM的构造函数(创建指向/要绑定的实例)。
在另一个类中(在我的程序的主窗口的ViewModel代码中)我也在实例化ViewModel,即:
private SomeAstractBaseViewModel someViewModel = new SomeViewModel(); private SomeAstractBaseViewModel someOtherViewModel = new SomeOtherViewModel();
它们都是从超类inheritance的,我在主窗口的一个部分中显示不同视图的实例之间来回切换 – 按照我的意图。
所有这些都是另一个问题,但是当我删除之前实例化ViewModel的另一个“未使用”实例的有问题的xaml (在此答案的顶部)时,View将根据INotifyPropertyChanged机制进行更新。