强制重新读取XAML中绑定的GUI属性

时间:2016-08-30 07:14:32

标签: wpf user-interface refresh dependency-properties

也许这在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”。

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

1 个答案:

答案 0 :(得分:1)

您需要在ViewModel上实现INotifyPropertyChanged界面。

然后在条件设置器中,您将调用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));
        }
    }
}