I have a wpf listbox
with a custom item template which contains a rectangle.
The each item in the listbox
can be selected (only one at a time).
I want to add a behavior in which when a user clicks on a place which isn't the item (for instance, a blank spot on the listbox
, which is not an item), the selected item will become deselected.
Any ideas? Thanks.
For example with a simple listbox: item 1 item 2
The behavior that I'm looking for is when the user clicks on pixel 500 (which is a part of the listbox
but not on an item), the currently selected item will be deselected.
To assure that only one item is selected put this in the listbox:
then for the unselect when clicking somewhere, you can try to check this events
Regards,
The simple solution is to data bind a property to the
ListBox.SelectedItem
property and set it tonull
whenever you want to clear the selection:Then in code, you can just do this to clear the selection:
And when would you do that? You can attach a handler to the
PreviewMouseLeftButtonDown
event of theWindow
, or any other control in your UI. In the handler method, you could do a hit test to see what the item the user clicked on was:See the
VisualTreeHelper.HitTest Method (Visual, Point)
for more help with this part.Then maybe something like this:
Of course, there are many ways to do this, and you'll have to fill in the few blank spots that I left, but you should get the idea.
EDIT >>>
The generic
GetParentOfType
method is a custom Extension Method that is defined in a separate class namedDependencyObjectExtensions
:Try ensuring your ListBox's background color is 'Transparent'
For
The each item in the listbox can be selected (only one at a time).
You can come up with one of followings
1- Disable the item after it is selected.
2- Maintain a list at backend to mark each index selectable or unselectable.