Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top