If you want an MVVM
style then I would suggest using System.Windows.Interactivity
and use `Behaviors.
Sample usage.
Behavior class
public class ListBoxBehavior : Behavior<ListBox>
{
public static readonly DependencyProperty AddedItemsProperty =
DependencyProperty.Register("AddedItems", typeof (List<object>), typeof (ListBoxBehavior), new PropertyMetadata(new List<object>()));
public List<object> AddedItems
{
get { return (List<object>) GetValue(AddedItemsProperty); }
set { SetValue(AddedItemsProperty, value); }
}
public static readonly DependencyProperty RemovedItemsProperty =
DependencyProperty.Register("RemovedItems", typeof(List<object>), typeof(ListBoxBehavior), new PropertyMetadata(new List<object>));
public List<object> RemovedItems
{
get { return (List<object>) GetValue(RemovedItemsProperty); }
set { SetValue(RemovedItemsProperty, value); }
}
protected override void OnAttached()
{
base.OnAttached();
var observableCollection = AssociatedObject.ItemsSource as ObservableCollection<object>;
if (observableCollection != null)
{
observableCollection.CollectionChanged += ItemsSourceOnCollectionChanged;
}
}
protected override void OnDetaching()
{
base.OnDetaching();
var observableCollection = AssociatedObject.ItemsSource as ObservableCollection<object>;
if (observableCollection != null)
{
observableCollection.CollectionChanged -= ItemsSourceOnCollectionChanged;
}
}
private void ItemsSourceOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
{
AddedItems.Clear();
RemovedItems.Clear();
switch (notifyCollectionChangedEventArgs.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (var newItem in notifyCollectionChangedEventArgs.NewItems)
{
AddedItems.Add(newItem);
}
break;
case NotifyCollectionChangedAction.Remove:
foreach (var newItem in notifyCollectionChangedEventArgs.NewItems)
{
RemovedItems.Add(newItem);
}
break;
}
}
}
XAML
<ListBox>
<i:Interaction.Behaviors>
<ListBoxBehavior AddedItems="{Binding AddedItems}"/>
<ListBoxBehavior AddedItems="{Binding RemovedItems}"/>
</i:Interaction.Behaviors>
</ListBox>
What happens is that the events that are subscribed is encapsulated in the behavior class and you can now create a binding to the dependency property that is associated with the class which is the ListBox
.