我有一个wpf TreeView,它有一个动态itemssource。用户可以在运行时添加和删除项目。 我错过了一个事件,它给了我添加到treeviews itemsSource中的当前添加的UIElement。所以我想我需要切换到OnCollectionChanged。集合更改时如何获得UIElement?
这是我有:
// 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,不如我就可以了,不想持有该视图模型视图的任何元素。 我喜欢在添加项目时触发一个事件,该项目在其发件人或EventArgs中提供了新添加的UIElement。
我已经尝试过ItemContainerGenerator类,但它在viewmodel中没有用,因为它需要一个UIElement控件。
我在“Drop”事件中处理添加项目。创建一个新的viemodel,它绑定到分层树视图数据模板。所以在“Drop”中,我有我的数据项,但我还想在新添加的项目上调用类似FrameworkElement.BringIntoView()的东西。 – deafjeff
为了在MVVM中实现这种类型的功能(需要使用类似'BringIntoView'的事件),我们创建了'Attached Properties'。 – Sheridan
更好:我们使用附加属性创建行为。我想我正在走向正确的道路。 – deafjeff