-1

I have a wpf Treeview which has a dynamic itemssource. The User can add and remove items at runtime. I'm missing an event which gives me the currently added UIElement that was added to the treeviews itemsSource. So I guess I need to switch to OnCollectionChanged.

This is what I have:

// 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;
            }
        }
    }

Im following MVVM, as good as I can, and don't want to hold any view elements in the viewmodel. I like to have an event that is fired when an item is added, which provides the new added UIElement in its sender or EventArgs.

I already tried ItemContainerGenerator class, but it's not useful inside a viewmodel since it requires already a UIElement Control.

deafjeff
  • 754
  • 7
  • 25

1 Answers1

1

You seem to be looking at this problem from the wrong direction... in MVVM, you can pretty much forget about the UI for the most part. So, instead of thinking how to get hold of the item that the user added into the collection control in the UI, think about accessing the data object that you added to the data collection in the view model that is data bound to the UI collection control in response to an ICommand that was initiated by the user.

So to me, it sounds like you need to implement an ICommand that is connected to a Button in the UI, where you add the new item into the data bound collection rather than any event. In this way, you'll always know the state of all of your data items.

Sheridan
  • 68,826
  • 24
  • 143
  • 183
  • I handle adding items in the "Drop" event. A new viemodel is created, which is bound to a hierarchical treeview datatemplate. So in "Drop", I have my dataitem, but I additionally like to call something like FrameworkElement.BringIntoView() on the new added item. – deafjeff Oct 23 '13 at 10:08
  • To implement that type of functionality (that require using events like `BringIntoView`) in MVVM, we create `Attached Properties`. – Sheridan Oct 23 '13 at 10:15
  • better: we create behaviors using attached properties. I think I'm coming to the right way.. – deafjeff Oct 23 '13 at 10:20