WPF ListBox改写模板,双击选中和删除问题

ListBox控件中,修改样式ItemTemplate,中外层为Grid,左侧为TextBlock显示内容,右侧为Button,button主要响应删除功能,双击文本,选中内容添加到指定区域;

首先来看看前端XAML设计


	
		
			
				
					
					
				
				
				

后台实现代码

private void Listbox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
	if (Dic_ListBox.SelectedItem != null)
	{
		Dictionary model = Dic_ListBox.SelectedItem as Dictionary;
		if (model != null)
		{
		//处理事件
		}
	}
}

public class Dictionary
{
       public int Dict_id { get; set; }
       public string Dict_name { get; set; }
}

private void Del_Click(object sender, RoutedEventArgs e)
{
	Button btn = sender as Button;
	if (btn != null)
	{
		Dictionary model = btn.CommandParameter as Dictionary;
		if (model != null)
		{
			m_DictionaryList.Remove(model);
			Dic_ListBox.ItemsSource = null;
			Dic_ListBox.ItemsSource = m_DictionaryList;
		}
	}
}

但是在测试过程中发现问题:

异常问题1:使用ListBox中的MouseDoubleClick,双击Button也触发选中,并且删除;
异常问题2:快速双击Button响应Click事件或者MouseDown事件,删除两个Item子项,而不是一个item项;
解决问题1:去除ListBox中的MouseDoubleClick事件,在Grid中添加MouseLeftButtonDown事件,响应双击文本功能;注意文本显示框要设置高度,不然点击空白处,不想要MouseDoubleClick事件
解决问题2:采用Button的Click事件,根据鼠标模拟双击事件的时间,间隔300ms内为双击,300ms内多次点击Button只响应一次;

解决代码参考如下:


	
		
			
				
					
					
				
				
				
private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
	if (e.LeftButton == MouseButtonState.Pressed && e.ClickCount == 1)
	{
		if (e.OriginalSource != null && e.OriginalSource is TextBlock)
		{
			var control = e.OriginalSource as FrameworkElement;
			if (control == null || control.DataContext == null)
				return;
		}
	}
	else if (e.LeftButton == MouseButtonState.Pressed && e.ClickCount >= 2)
	{
		if (e.OriginalSource != null && e.OriginalSource is Button)
		{
			e.Handled = true;
		}
		else if (e.OriginalSource != null && e.OriginalSource is TextBlock)
		{
			var control = e.OriginalSource as FrameworkElement;
			if (control == null || control.DataContext == null)
				return;
			 var dic = Dic_ListBox.SelectedItem as Dictionary;
		}
	}
}

List m_DictionaryList = null;//存储列表数据
DateTime m_mouseClikTime = DateTime.Now;
private void Del_Click(object sender, RoutedEventArgs e)
{
	if (DateTime.Now.Subtract(m_mouseClikTime).TotalMilliseconds > 300)
	{
		m_mouseClikTime = DateTime.Now;
		Button btn = sender as Button;
		if (btn != null)
		{
			Dictionary model = btn.CommandParameter as Dictionary;
			if (model != null)
			{
				m_DictionaryList.Remove(model);
				Dic_ListBox.ItemsSource = null;
				Dic_ListBox.ItemsSource = m_DictionaryList;
			}
		}
	}
}


public class Dictionary
{
       public int Dict_id { get; set; }
       public string Dict_name { get; set; }
}

 

你可能感兴趣的:(#,WPF,遇坑记,ListBox双击删除问题)