问题
The WPF Treeview responds to + and - keystrokes to expand and collapse nodes in the tree. Great!
Is there an existing command I can bind my toolbar buttons or menu items to to perform the same actions in the treeview? I don't see anything related to expand/collapse in the stock command constants.
回答1:
The TreeView
handles the expansion of a TreeViewItem
with the mouse by binding ToggleButton.IsChecked
to TreeViewItem.IsExpanded
in the ControlTemplate
and handles expansion with the keyboard in an override TreeViewItem.OnKeyDown
. So, no, it doesn't use commands in its implementation.
But you can add your own commands without much effort. In this example, I've added a behavior to a 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 that 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 behaviors, first add this namespace:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
and add the corresponding reference to your project.
来源:https://stackoverflow.com/questions/4731718/does-treeview-use-command-bindings-for-expand-collapse