附加属性作用于多选控件,用于获取所有选中项
using System.Collections; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; /// <summary> /// 附加属性作用于多选控件,用于获取所有选中项 /// </summary> public static class SelectorExt { public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.RegisterAttached("SelectedItems", typeof(IList), typeof(SelectorExt), new PropertyMetadata(OnSelectedItemsChanged)); public static IList GetSelectedItems(DependencyObject obj) { return obj.GetValue(SelectedItemsProperty) as IList; } public static void SetSelectedItems(DependencyObject obj, IList value) { obj.SetValue(SelectedItemsProperty, value); } private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d == null) return; //MultiSelector MultiSelector multiSelector = d as MultiSelector; if (multiSelector != null) { multiSelector.SelectionChanged -= MultiSelector_SelectionChanged; multiSelector.SelectedItems.Clear(); if ((e.NewValue as IList) != null) { foreach (object item in e.NewValue as IList) { multiSelector.SelectedItems.Add(item); } } multiSelector.SelectionChanged += MultiSelector_SelectionChanged; return; } ListBox listbox = d as ListBox;//增加Listbox多选附加,ListView继承ListBox,也可以使用 if (listbox != null) { listbox.SelectionChanged -= MultiSelector_SelectionChanged; listbox.SelectedItems.Clear(); if ((e.NewValue as IList) != null) { foreach (object item in e.NewValue as IList) { listbox.SelectedItems.Add(item); } } listbox.SelectionChanged += MultiSelector_SelectionChanged; return; } } private static void MultiSelector_SelectionChanged(object sender, SelectionChangedEventArgs e) { IList source = GetSelectedItems(sender as DependencyObject); if (source == null) return; foreach (var item in e.AddedItems) source.Add(item); //添加选中的项 foreach (var item in e.RemovedItems) source.Remove(item); //移除选中项 } }
转载保留源出处即可,商业使用请自行鉴别,使用本博客中公开内容做任何违法犯罪于本作者无关