我遵循MVVM模式。我已经创建了自定义列表框控件,将其命名为ExtendedListbox。
在xmal中,我定义了listbox和ItemSource属性。
<ExtendedListBox ItemsSource="{Binding Students}">
在我的视图模型中,我将学生定义为ObservableCollection。
公共可观测集合<Student>
学生;
运行时,我正在学生集合中添加/删除学生对象。
在我的ExtendedListBox控件类中,我想知道从listbox的数据源添加/删除哪个对象。
当从listbox的数据源添加或删除任何项目时,是否会触发任何事件?
如果您想要MVVM
样式,那么我建议使用System.Windows.Interactivity
并使用`Behaviors。
示例用法。
行为类
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>
所发生的情况是,订阅的事件被封装在行为类中,您现在可以创建与ListBox
类关联的依赖属性的绑定。