gpt4 book ai didi

c# - 让 ObservableCollection 触发更新

转载 作者:行者123 更新时间:2023-11-30 14:42:56 25 4
gpt4 key购买 nike

所以我有一些类似的东西

private  ObservableCollection<ViewModel> _internal;

public ObservableCollection<ViewModel> BoundInternal{get;set}; //this is Binded in the Itemssource like ItemSource={Binding BoundInternal}

现在在我的代码中我做了类似的事情

BoundInternal=_internal,但是问题是 BoundInternal 没有触发任何 collectionChanged 事件。我必须使用 Add 方法。所以我想知道是否有解决方案。

最佳答案

这是我怀疑您的代码应该看起来像的样子(尽管它与您当前所做的不太匹配):-

public class YourClassHoldingThisStuff : INotifyProperyChanged
{
private ObservableCollection<ViewModel> _internal;

public ObservableCollection<ViewModel> BoundInternal
{
get { return _internal; }
set
{
_internal = value;
NotifyPropertyChanged("BoundInternal");
};
}
public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new ProperytChangedEventArgs(name));
}
}

在这种情况下,_internal 字段直接成为 BoundInternal 值的来源,您应该只通过 BoundInternal 分配它,(不要'直接给 _internal 赋值)。当发生这种情况时,当前绑定(bind)到它的任何东西都会被告知更改。

如果出于某种原因您确实需要将 _internal 维护为与 BoundInternal 的支持字段分开的引用,那么:-

public class YourClassHoldingThisStuff : INotifyProperyChanged
{
private ObservableCollection<ViewModel> _internal;
private ObservableCollection<ViewModel> _boundInternal;

public ObservableCollection<ViewModel> BoundInternal
{
get { return _boundInternal; }
set
{
_boundInternal = value;
NotifyPropertyChanged("BoundInternal");
};
}
public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new ProperytChangedEventArgs(name));
}
}

现在,当您执行 BoundInternal = _internal 时,在您的代码中的某个位置,绑定(bind)到它的任何对象都会收到更改通知。

关于c# - 让 ObservableCollection 触发更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2616040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com