在 XAML 中强制重新读取 GUI 属性

Force re-read GUI property bound in XAML

也许这在 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"; }
}

GroupBox 显示 "B"。很好。
但是稍后我们更改 Condition= true ,我希望 GroupBox 自行刷新,所以再次读出 Caption,这将是 "A".

我怎样才能以最简单的方式做到这一点?
谢谢

您需要在您的 ViewModel 上实现 INotifyPropertyChanged 接口。

然后在 Condition 的 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));
        }
    }
}