TreeView handles the TreeViewItem extension with the mouse, attaching ToggleButton.IsChecked to TreeViewItem.IsExpanded in the ControlTemplate and processing the extension with the keyboard overrides TreeViewItem.OnKeyDown . Thus, no, he does not use commands in his implementation.
But you can add your own teams without much effort. In this example, I added behavior to the TreeView so that it responds to the standard Open and Close application commands:
<DockPanel> <Menu DockPanel.Dock="Top"> <MenuItem Header="Open" CommandTarget="{Binding ElementName=treeView1}" Command="Open"/> <MenuItem Header="Close" CommandTarget="{Binding ElementName=treeView1}" Command="Close"/> </Menu> <TreeView> <i:Interaction.Behaviors> <local:TreeViewCommandsBehavior/> </i:Interaction.Behaviors> <TreeViewItem Header="Root"> <TreeViewItem Header="Item1"> <TreeViewItem Header="Subitem1"/> <TreeViewItem Header="Subitem2"/> </TreeViewItem> <TreeViewItem Header="Item2"> <TreeViewItem Header="Subitem3"/> <TreeViewItem Header="Subitem4"/> </TreeViewItem> </TreeViewItem> </TreeView> </DockPanel>
and here is the behavior that makes it work:
public class TreeViewCommandsBehavior : Behavior<TreeView> { private TreeViewItem selectedTreeViewItem; protected override void OnAttached() { AssociatedObject.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(TreeViewItem_Selected)); AssociatedObject.CommandBindings.Add(new CommandBinding(ApplicationCommands.Open, CommandExecuted)); AssociatedObject.CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, CommandExecuted)); } private void TreeViewItem_Selected(object sender, RoutedEventArgs e) { selectedTreeViewItem = e.OriginalSource as TreeViewItem; } private void CommandExecuted(object sender, ExecutedRoutedEventArgs e) { bool expand = e.Command == ApplicationCommands.Open; if (selectedTreeViewItem != null) selectedTreeViewItem.IsExpanded = expand; } }
If you are not familiar with the behavior, first add this namespace:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
and add the appropriate link to your project.
Rick sladkey
source share