wpf Listbox 實現按住ctrl鍵來取消選中
阿新 • • 發佈:2018-12-10
1. 首先繼承一個listbox,來獲得按住ctrl鍵時,點選的item
public class ListBoxEx : ListBox { public BeatTemplateWave GetAnitem() { var obj = this.AnchorItem; if (obj != null) { Type type = obj.GetType(); System.Reflection.PropertyInfo propertyInfo = type.GetProperty("Item", BindingFlags.Instance | BindingFlags.NonPublic); System.Reflection.PropertyInfo propertyInfo2 = type.GetProperty("Index", BindingFlags.Instance| BindingFlags.NonPublic); BeatTemplateWave value_Old = (BeatTemplateWave)propertyInfo.GetValue(obj, null); //獲取屬性值 return value_Old; } else { return null; } }
//重寫選中 public void Setlist(List<BeatTemplateWave> list) { this.SetSelectedItems(list); }
}
2 在listbox 的呼叫處: 獲得listbox 的選中項:SelectedItemsList
3 在mouseleftdown事件裡面新增處理程式
private void MouseLeftButtonUpHandler(ElementMouseButtonEventMerge embem) { ListBoxEx listbox = (embem.Sender as ListBoxEx); if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) { List<BeatTemplateWave> selectlist = new List<BeatTemplateWave>(); var obj = (embem.Sender as ListBoxNoWheelEx).GetAnitem(); if (SelectedItemsList != null) { var templist = SelectedItemsList.IListToCollection<BeatTemplateWave>(); if (obj != null) {
//判斷滑鼠點選的項在不在選中的裡面,如果不在,則加入臨時集合,如果在選中項裡面,則不加入臨時集合,if (templist.Any(p => p.R == obj.R)) { foreach (BeatTemplateWave a in templist) { if (a.R == obj.R) { } else {
selectlist.Add(a); } } } else { selectlist.Add(obj); selectlist.AddRange(templist); } } else { selectlist.AddRange(templist); } listbox.Setlist(selectlist); //重新選中 SelectedItemsList = selectlist;//將臨時集合賦值給選中項 重寫選中} return; } else { if (listbox.SelectedItems != null) { SelectedItemsList = listbox.SelectedItems; var item = SelectedItemsList; if (item.Count == 0) return; } } }