我在TreeView中有一个ContextMenu,它包含一个TextBox和一个Button。
function setText(arr) {
$.each(arr, function(i, obj) {
obj.text = obj.name;
if (obj.children && obj.children.length) {
setText(obj.children);
}
});
}
setText(data);
就鼠标操作而言,这可以按预期工作。右键单击打开菜单,然后用户可以填写文本框并左键单击按钮以执行AddFolderCommand。
但是,用户还希望按下Enter / Return键时触发按钮,这样他们就可以在输入文字后坚持使用键盘。
此时,按Enter / Return键会关闭ContextMenu,焦点会切换到TreeView。但底层命令不会执行。
我尝试在按钮上设置<TreeView ItemsSource="{Binding Folders}">
<TreeView.ContextMenu>
<ContextMenu IsOpen="{Binding Path=PlacementTarget.Tag.DataContext.ContextOpen, Mode=TwoWay, RelativeSource={RelativeSource Self}}">
<StackPanel Orientation="Vertical">
<TextBox Text="{Binding Path=PlacementTarget.Tag.DataContext.AddFolderName, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"></TextBox>
<Button Content="Create here" IsDefault="True"
Command="{Binding Path=PlacementTarget.Tag.DataContext.AddFolderCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}">
</Button>
</StackPanel>
</ContextMenu>
</TreeView.ContextMenu>
<TreeView>
,但其行为不会改变。屏幕上一次只能打开一个ContextMenu。我们正在使用MVVM,因此如果可能的话,我更愿意避免使用代码隐藏解决方案。如何在按键上触发命令?
答案 0 :(得分:1)
<TreeView ItemsSource="{Binding Folders}">
<TreeView.ContextMenu>
<ContextMenu IsOpen="{Binding Path=PlacementTarget.Tag.DataContext.ContextOpen, Mode=TwoWay, RelativeSource={RelativeSource Self}}">
<StackPanel Orientation="Vertical">
<TextBox Text="{Binding Path=PlacementTarget.Tag.DataContext.AddFolderName, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"></TextBox>
<Button Content="Create here" IsDefault="True"
Command="{Binding Path=PlacementTarget.Tag.DataContext.AddFolderCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}">
</Button>
<StackPanel.InputBindings>
<KeyBinding Gesture="Enter" Command ="{Binding Path=PlacementTarget.Tag.DataContext.AddFolderCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"/>
</StackPanel.InputBindings>
</StackPanel>
</ContextMenu>
</TreeView.ContextMenu>
<TreeView>
这应该可以做到这一点,而不必离开xaml。请注意<StackPanel.InputBindings>
部分