关于xaml:在Return / Enter上的ContextMenu中触发WPF MVVM按钮

Triggering WPF MVVM Button in ContextMenu on Return/Enter

我在TreeView内部有一个ContextMenu,其中包含一个TextBox和一个Button。

1
2
3
4
5
6
7
8
9
10
11
12
<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>

就鼠标操作而言,这可以按预期工作。右键单击将弹出菜单,然后用户可以填写文本框,然后在按钮上单击鼠标左键以执行AddFolderCommand。

但是,用户还希望在按下Enter / Return键时触发该按钮,因此他们只需在输入文本后按住键盘即可。

此刻,按Enter / Return键将关闭ContextMenu,并将焦点切换到TreeView。但是基本命令不会执行。

我尝试在按钮上设置IsDefault="True",但是其行为不会改变。一次打开的屏幕上只能有一个ContextMenu。我们正在使用MVVM,因此,如果可能的话,我宁愿避免使用代码隐藏解决方案。如何在按键上触发命令?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<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>部分