How do you get the currently highlighted/selected node from a TreeView
control? Based on the documentation here it should be possible to iterate through the control's SelectedNodes
property but its always empty.
EDIT: This turns out to be an actual bug with XAML, tracked here. Until it's fixed, the accepted answer does fine as work-around.
Context: I'm working on a simple demo application to explore the TreeView
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 ICommand
. I have already gotten it working from the TreeViewItem
DataTemplate
as a button and as a flyout menu. I couldn't see a clean way to reuse the ICommand
in a keyboard shortcut.
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.
I have an event handler on the TreeView
control:
<controls:TreeView x:Name="TreeDataBound"
ItemsSource="{Binding Path=TreeSource, Mode=TwoWay}"
ItemTemplateSelector="{StaticResource TreeItemTemplateSelector}"
SelectionMode="Single"
KeyDown="Tree_KeyDown">
The event handler should be looping through the selected nodes, although I think with SelectionMode="Single"
the enumerable should only have one item.
private void Tree_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Delete)
{
foreach (var element in TreeDataBound.SelectedNodes)
{
// Delete the item
}
}
}
SelectedNodes
appears to always be empty, even when one of the TreeView iems is highlighted. In the debugger SelectedNodes
appears as type of System.__ComObject
with no accessible properties, so I can't inspect it any further.
Any thoughts or suggestions for a better approach?
Read more here: https://stackoverflow.com/questions/56766785/uwp-get-selected-nodes-from-treeview-control
Content Attribution
This content was originally published by daedalus12 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.