所以我有一些类似的东西
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
)。当发生这种情况时,当前绑定到它的任何东西都将被告知更改。如果出于某些原因您确实确实需要将
_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
的某个点时,绑定到它的任何内容都将被告知更改。关于c# - 让ObservableCollection触发更新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2616040/