title: UWP Get selected nodes from TreeView control
body: <p>How do you get the currently highlighted/selected node from a <code>TreeView</code> control? Based on the documentation <a href="https://docs.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/tree-view#item-selection" rel="nofollow noreferrer">here</a> it should be possible to iterate through the control's <code>SelectedNodes</code> property but its always empty.</p>
  
  <hr>
  
  <p><strong>EDIT:</strong> This turns out to be an actual bug with XAML, tracked <a href="https://github.com/microsoft/microsoft-ui-xaml/issues/124" rel="nofollow noreferrer">here</a>. Until it's fixed, the accepted answer does fine as work-around. </p>
  
  <hr>
  
  <p>Context: I'm working on a simple demo application to explore the <code>TreeView</code> control. I'm trying to add a keyboard shortcut to delete the currently active/selected node. I have the delete functionality in a RelayCommand class that implements <code>ICommand</code>. I have already gotten it working from the <code>TreeViewItem</code> <code>DataTemplate</code> as a button and as a flyout menu. I couldn't see a clean way to reuse the <code>ICommand</code> in a keyboard shortcut.</p>
  
  <p>Image of the app with the last-clicked item highlighted; I need to access this TreeViewItem in the code-behind so I can delete it when the TreeView has focus and the "Delete" key is pressed. 
  <a href="https://i.stack.imgur.com/aEErf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aEErf.png" alt="TreeViewExample"></a></p>
  
  <p>I have an event handler on the <code>TreeView</code> control:</p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;controls:TreeView x:Name="TreeDataBound"
      ItemsSource="{Binding Path=TreeSource, Mode=TwoWay}"
      ItemTemplateSelector="{StaticResource TreeItemTemplateSelector}"
      SelectionMode="Single"
      KeyDown="Tree_KeyDown"&gt;
  </code></pre>
  
  <p>The event handler should be looping through the selected nodes, although I think with <code>SelectionMode="Single"</code> the enumerable should only have one item. </p>
  
  <pre class="lang-cs prettyprint-override"><code>private void Tree_KeyDown(object sender, KeyRoutedEventArgs e)
  {
      if (e.Key == Windows.System.VirtualKey.Delete)
      {
          foreach (var element in TreeDataBound.SelectedNodes)
          {
              // Delete the item 
          }
      }
  }
  
  </code></pre>
  
  <p><code>SelectedNodes</code> appears to always be empty, even when one of the TreeView iems is highlighted. In the debugger <code>SelectedNodes</code> appears as type of <code>System.__ComObject</code> with no accessible properties, so I can't inspect it any further. </p>
  
  <p>Any thoughts or suggestions for a better approach?</p>