wpf Listbox 实现按住ctrl键来取消选中
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; } } }