我有一个wpf Treeview,它有一个动态的itemssource。用户可以在运行时添加和删除项目。 我错过了一个事件,它给了我当前添加的添加到treeviews itemsSource的UIElement。所以我想我需要切换到OnCollectionChanged。
这就是我所拥有的:
// MyItemViewModel is a viewmodel for a TreeViewItem
// MyCollection is bound to hte Treeview's ItemsSource
public class MyCollection : ObservableCollection<MyItemViewModel>
{
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
// i like to have the UIelement which was added to the collection
// (e.NewItems contains the FrameworkElement's DataContext)
break;
}
}
}
我跟随MVVM,尽我所能,并且不想在viewmodel中保存任何视图元素。 我喜欢在添加项目时触发事件,该事件在其sender或EventArgs中提供新添加的UIElement。
我已经尝试过ItemContainerGenerator类,但它在viewmodel中没用,因为它需要一个UIElement控件。
答案 0 :(得分:1)
你好像从错误的方向看这个问题......在MVVM中,你几乎可以忘掉UI的大部分内容。因此,不要考虑如何获取用户添加到UI中的集合控件中的项目,而是考虑访问您添加到<数据对象 < em>视图模型中的数据收集 数据绑定到UI集合控件,以响应用户发起的ICommand
。
所以对我而言,听起来你需要在UI中实现与ICommand
相关联的Button
,其中你将新项目添加到数据中绑定集合而不是任何事件。通过这种方式,您将始终了解所有数据项的状态。