【问题标题】:Triggering WPF MVVM Button in ContextMenu on Return/EnterReturn/Enter 时触发 ContextMenu 中的 WPF MVVM 按钮
【发布时间】:2016-03-08 16:35:07
【问题描述】:

我在 TreeView 中有一个 ContextMenu,它包含一个 TextBox 和一个 Button。

<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,所以如果可能的话,我宁愿避免使用代码隐藏解决方案。如何触发按键上的命令?

【问题讨论】:

  • 您的ViewModel 不会以任何方式从KeyPress 中受益,因此代码隐藏将是我的初始和最终方法,除了命令仅由 UI 使用,因此没关系如果它被后面的代码调用。别害怕,一切都会好的:-)
  • 我也会使用 KeyPress 事件,如果它是 Enter 键,则触发 CreateButton.Click 事件。这种 View-Specific 行为非常适合放在 View 后面的代码中。

标签: wpf xaml mvvm


【解决方案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。注意&lt;StackPanel.InputBindings&gt; 部分

【讨论】:

    猜你喜欢
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    相关资源
    最近更新 更多