2016-03-08 50 views
0

我在TreeView中有一個ContextMenu,它包含一個TextBox和一個Button。在ContextMenu上觸發WPF MVVM按鈕返回/輸入

<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,所以如果可能的話,我寧願避免使用代碼隱藏解決方案。我怎樣才能在按鍵上觸發命令?

+2

您的'ViewModel'不會以任何方式從'KeyPress'中受益,因此代碼隱藏將是我的初始和最終方法,除了命令完全由UI使用,因此無關緊要它由後面的代碼調用。不要害怕,它會好起來的:-) – XAMlMAX

+1

我也會使用一個KeyPress事件,如果它的回車鍵,觸發CreateButton.Click事件。這種特定於View的行爲非常適合放置在View背後的代碼中。 – Rachel

回答

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>部分