【问题标题】:How to get INotifyPropertyChanged binding to change when it is bound to a getter property?如何让 INotifyPropertyChanged 绑定在绑定到 getter 属性时更改?
【发布时间】:2015-04-01 21:40:16
【问题描述】:

我有一个这样的虚拟机

class Vm : Notifiable
{
    public string Name 
    {
        get { return _Name; }
        set { _Name = value; OnPropertyChanged("Name"); }
    }
    private _Name = "";
}

还有一个这样的

class CollectionVm : Notifiable
{
    public ObservableCollection<Vm> Vms {get;set;}
    public Vm Selected 
    {
        get { return _Selected; }
        set { _Selected= value; OnPropertyChanged("Selected"); }
    }
    Vm _Selected = null;
}

还有三分之一是这样的

class OuterVm : Notifiable
{
    CollectionVm _collection;
    public Vm Display
    {
        get {return _collection.Selected; }
    }
}

还有这样的绑定

<TextBlock Text={Binding Display.Name}/>

我的问题是,当集合中的选择发生变化时,文本块不会更新。我怎样才能让它这样做?

【问题讨论】:

    标签: c# wpf xaml inotifypropertychanged


    【解决方案1】:

    这需要一种机制,您可以通过该机制在OuterVm 中引发PropertyChanged 事件。

    一个简单的选择是订阅事件并传递它们:

    class OuterVm : Notifiable
    {
        public OuterVm()
        {
            // initialize _collection
            _collection.PropertyChanged += (o,e) =>
            {
                if (e.PropertyName == "Selected")
                    OnPropertyChanged("Display");
            };
        }
        CollectionVm _collection;
        public Vm Display
        {
            get {return _collection.Selected; }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-15
      • 2015-10-07
      • 2021-09-01
      • 1970-01-01
      • 2020-03-28
      • 2019-03-24
      • 1970-01-01
      • 2017-06-27
      • 1970-01-01
      相关资源
      最近更新 更多