也许这是一个简单的事情在WPF,有人可以帮助吗?
XAML:<GroupBox Header="{Binding Path=Caption}" Name="group">
c#: //simplified code
bool _condition = false;
bool Condition
{
get { return _condition; }
set { _condition = value; }
}
public string Caption
{
get { return Condition ? "A" : "B"; }
}
组框显示为"B"。好。
但是后来我们改变了Condition= true
,我想让GroupBox自己刷新,所以再次读出标题,它将是"A"。
我怎样才能用最简单的方法做到呢?
由于
你需要在你的ViewModel上实现INotifyPropertyChanged接口
然后在条件的setter中你会调用OnPropertyChanged("Caption")来通知xaml绑定机制你的属性已经改变,需要重新评估。
public class ViewModel : INotifyPropertyChanged
{
// These fields hold the values for the public properties.
bool _condition = false;
bool Condition
{
get { return _condition; }
set {
_condition = value;
NotifyPropertyChanged();
NotifyPropertyChanged("Caption");
}
}
public string Caption
{
get { return Condition ? "A" : "B"; }
}
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}