我有一个文本块:
<TextBlock HorizontalAlignment="Left" Name="StatusText" Margin="0,20" TextWrapping="Wrap" Text="{Binding StatusText}">
... Status ...
</TextBlock>
代码后置文件:
public StatusPage()
{
InitializeComponent();
this.DataContext = new StatusPageViewModel(this);
}
并且在 viewModel 中:
private string _statusText;
/// <summary>
/// Status text
/// </summary>
public string StatusText
{
get { return _statusText; }
set { _statusText = value; }
}
并在viewModel中的函数中:
string statusText = Status.GetStatusText();
this.StatusText = statusText;
GetStatusText()
返回类似于 "工作完成" 的字符串等。该函数的返回值被赋给 this.StatusText
,但是 TextBlock 的文本属性没有改变,仍然显示占位符 "... 状态 ..."。
我知道有类似这样的问题 --> 点击 <-- 但是在阅读了这篇文章之后,我仍然无法找到解决方案。
@更新
按照您的建议,我更新了我的代码,现在它是这样的:
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
/// <summary>
/// Raises the PropertyChange event for the property specified
/// </summary>
/// <param name="propertyName">Property name to update. Is case-sensitive.</param>
public virtual void RaisePropertyChanged(string propertyName)
{
OnPropertyChanged(propertyName);
}
/// <summary>
/// Raised when a property on this object has a new value.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises this object's PropertyChanged event.
/// </summary>
/// <param name="propertyName">The property that has a new value.</param>
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
#endregion // INotifyPropertyChanged Members
}
但它仍然不起作用
MainWindow : Window, INotifyPropertyChanged
。 - Reahreic