撤销选择在WPF列表框具有扩展选择模式 [英] Deselection on a WPF listbox with extended selection mode

查看:115
本文介绍了撤销选择在WPF列表框具有扩展选择模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扩展的选择模式的简单列表框。选择作品几乎完全没有像它在资源管理器中。但是,取消选择并没有真正的工作都那么好。我要的是,当我点击的东西在我想要的所有元素要取消选择的列表框元素的范围之外。我似乎并没有表现在默认情况下是这样,我做了一个肮脏的黑客涉及的SelectionChanged和mouseup破解它。但是,必须有一个更好的办法。任何想法?

I have a simple listbox with extended selection mode. Selection works almost perfectly fine like it works in explorer. But deselection doesn't really work all that well. What I want is that when I click on something outside the range of elements in the listbox I want all elements to be deselected. I doesn't seem to behave that way by default and I did a dirty hack involving selectionchanged and mouseup to hack it up. But there has to be a better way. Any ideas?

推荐答案

这并不是说脏在取消的功能添加,你是在正确的轨道上。主要的问题是,默认情况下列表框里面的ListBoxItems将在伸展一路,使得它非常艰难的不可以点击之一。

It isn't that dirty to add in the deselection functionality, and you're on the right track. The main issue is that by default the ListBoxItems inside the ListBox will stretch all the way across, making it pretty tough to not click on one.

下面是一个例子ListBox中的修改默认的ItemContainerStyle,这样的项目只是占用列表的左侧,还有就是项目之间有一些间隔为好。

Here's an example ListBox that modifies the default ItemContainerStyle so that the items just take up the left side of the list and there is some spacing between the items as well.

<ListBox SelectionMode="Extended"
		 Width="200" Mouse.MouseDown="ListBox_MouseDown">
	<ListBox.ItemContainerStyle>
		<Style TargetType="{x:Type ListBoxItem}">
			<Setter Property="Background"
					Value="LightBlue" />
			<Setter Property="Margin"
					Value="2" />
			<Setter Property="Padding"
					Value="2" />
			<Setter Property="Width"
					Value="100" />
			<Setter Property="HorizontalAlignment"
					Value="Left" />
		</Style>
	</ListBox.ItemContainerStyle>
	<ListBoxItem >Item 1</ListBoxItem>
	<ListBoxItem >Item 2</ListBoxItem>
	<ListBoxItem >Item 3</ListBoxItem>
	<ListBoxItem >Item 4</ListBoxItem>
</ListBox>

要取消选择的项目,我们只需要设置的SelectedItem为空的事件处理程序。当我们点击一​​个ListBoxItem的,它会处理MouseDown /点击等设置的SelectedItem或修改SelectedItems。正因为如此,当我们想要的,我们只处理MouseDown ListBox中的完全RoutedEvents的性质。当列表框里面的某个地方被点击,是不是一个项目的一部分。

To deselect the selected items we just need to set the SelectedItem to null in the EventHandler. When we click on a ListBoxItem, it will handle the MouseDown/Click etc to set the SelectedItem or modify the SelectedItems. Because of this, and the nature of the RoutedEvents we just handle the MouseDown in the ListBox exactly when we want. When somewhere inside the ListBox is clicked that isn't part of an item.

private void ListBox_MouseDown(object sender, MouseButtonEventArgs e)
{
	(sender as ListBox).SelectedItem = null;
}

这篇关于撤销选择在WPF列表框具有扩展选择模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆