Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deselect all selected items in a WPF treeview when clicking on some empty area?

Tags:

wpf

I've got a rather funny problem with WPF. I have a tree-view, and selecting items works fine so far. The problem is, I want to unselect the currently selected item when the user clicks inside the blank area of the treeview. By default, the treeview keeps the current item selected, and I have added a context-menu option to deselect it, which is rather hardcore:

// Note: This is done recursivly from the start, so it
// works for child items as well
treeView.ItemContainerGenerator.ContainerFromItem(treeView.SelectedItem) as TreeViewItem).IsSelected = false;

Moreover, this is counter-intuitive, as it requires the user to right-click first, and second, after deselecting it with this way, the user cannot select it any more by clicking on the item. How is this supposed to work?

Edit: Some more information: I've added a handler to the TreeView to handle mouse click events, but the sender is always a TreeView instance, even if I click directly on a TreeViewItem. If I add a handler to my TreeView.ItemTemplate instead (i.e. the first child in the template), I never get events when I click on the empty area (which is rather logical). The code looks like this:

    private void MyTreeView_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if ((sender as TreeViewItem) == null)
        {
            // Always triggered
            System.Diagnostics.Trace.Write("Empty area clicked");
        }
    } 

And the XAML for this is:

<TreeView x:Name="MyTreeView" Margin="3" MouseUp="MyTreeView_MouseUp">
like image 931
Anteru Avatar asked Jan 29 '09 10:01

Anteru


1 Answers

I found this to work much better for me. I check the originalsource which for me if it comes form a treeviewitem will be an image or a textblock. I also use a view object with a HierarchicalDataTemplate and the BasicTreeViewBase is the base class for all of my different objects. Here is the code.

private void TemplateTreeView_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (e.ChangedButton == MouseButton.Right && !(e.OriginalSource is Image) && !(e.OriginalSource is TextBlock))
        {
            BasicTreeViewBase item = TemplateTreeView.SelectedItem as BasicTreeViewBase;
            if (item != null)
            {
                TemplateTreeView.Focus();
                item.IsSelected = false;
            }
        }
    }
like image 111
Erin Avatar answered Oct 15 '22 20:10

Erin