2010-04-11 72 views
3

所以我要沿着拥有的ObservableCollection触发更新

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方法。所以我想知道是否有解决方案。

回答

4

这是我怀疑你的代码应该看起来像一样(尽管它并不完全是你正在做什么比赛): -

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,什么必然它会被告知更改。

2

Every ItemsControl有一个Items属性,它有一个Refresh()方法,您可以调用它来更新您的列表。

MyList.Items.Refresh()

+0

虽然我没有使用列表,但是我绑定了一个ItemsControl – 2010-04-11 04:34:09

+0

是的,我的代码只是一个示例,您的ItemsControl应该有Items属性仍然 – Mark 2010-04-11 04:36:03

+0

-1,Items属性是受保护的,所以您需要创建派生类访问它。它公开了一个没有'Refresh'方法的'IList '接口。 – AnthonyWJones 2010-04-11 07:43:25