【问题标题】:Force re-read GUI property bound in XAML [duplicate]强制重新读取 XAML 中绑定的 GUI 属性 [重复]
【发布时间】:2017-01-06 08:39:17
【问题描述】:

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

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

【问题讨论】:

  • 看来这是我需要的,让我调查一下,然后返回,谢谢

标签: wpf user-interface refresh dependency-properties


【解决方案1】:

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

然后在 Condition 的设置器中调用 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));
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-04-12
    • 2017-01-30
    • 2013-08-25
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    相关资源
    最近更新 更多