title: How to deselect all selected items in a WPF treeview when clicking on some empty area?
body: <p>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:</p>
  
  <pre><code>// 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;
  </code></pre>
  
  <p>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?</p>
  
  <p>Edit: Some more information: I've added a handler to the <code>TreeView</code> to handle mouse click events, but the sender is always a <code>TreeView</code> instance, even if I click directly on a <code>TreeViewItem</code>. If I add a handler to my <code>TreeView.ItemTemplate</code> 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:</p>
  
  <pre><code>    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");
          }
      } 
  </code></pre>
  
  <p>And the XAML for this is:</p>
  
  <pre><code>&lt;TreeView x:Name="MyTreeView" Margin="3" MouseUp="MyTreeView_MouseUp"&gt;
  </code></pre>