2009-10-26 34 views
3

我有一個帶有兩個文本框的WPF視圖。當用戶像Tab一樣按下鍵盤上的向下箭頭時,我想自動將焦點從第一個文本框向前移動到第二個文本框。移動焦點以響應XAML中的鍵盤事件

看來我應該能夠100%聲明地做到這一點,但由於某種原因,我認爲這樣做的命令似乎沒有做任何事情。這是我第一次嘗試不起作用:

<StackPanel> 
    <TextBox Text="Test"> 
     <TextBox.InputBindings> 
      <!-- I realize ComponentCommands.MoveFocusDown doesn't work... 
       This is just an example of what I've tried and the type 
       of answer I'm looking for --> 
      <KeyBinding Key="Down" Command="ComponentCommands.MoveFocusDown" /> 
     </TextBox.InputBindings> 
    </TextBox> 
    <TextBox></TextBox> 
</StackPanel> 

有沒有人有這方面的經驗?似乎我應該能夠使用InputBindings或EventTrigger來做到這一點。

我正在使用MVVM,這是一個查看問題。我可以在一個簡單的代碼隱藏(作爲一個觀點關注,這是合理的),但它只是覺得我失去了一些東西。

回答

5

我希望有人想出一些更優雅的東西,但這是我迄今爲止。它不是100%XAML,但它至少是通用的。

本示例顯示了一個帶有兩個按鈕和兩個文本框的窗口。向下箭頭循環它們之間的焦點。

我希望這會有所幫助。

<Window x:Class="WPF_Playground.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Window1" Height="300" Width="300" 
    > 
    <Window.CommandBindings> 
     <CommandBinding Command="ComponentCommands.MoveFocusDown" Executed="CommandBinding_Executed"/> 
    </Window.CommandBindings> 
    <StackPanel KeyboardNavigation.DirectionalNavigation="Cycle"> 
     <Button>Tester</Button> 
     <Button>Tester2</Button> 
     <TextBox Text="Test"> 
      <TextBox.InputBindings> 
       <KeyBinding Command="ComponentCommands.MoveFocusDown" Gesture="DOWN" /> 
      </TextBox.InputBindings> 
     </TextBox> 
     <TextBox Text="Test2"> 
      <TextBox.InputBindings> 
       <KeyBinding Command="ComponentCommands.MoveFocusDown" Gesture="DOWN" /> 
      </TextBox.InputBindings> 
     </TextBox> 
    </StackPanel> 
</Window> 

事件處理程序(沒有錯誤處理的話):

private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) 
{ 
    UIElement senderElement = sender as UIElement; 
    UIElement focusedElement = FocusManager.GetFocusedElement(senderElement) as UIElement; 
    bool result = focusedElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); 
    Debug.WriteLine(result); 
} 
+0

+1簡單哇!手勢對我來說是新事物 – 2009-10-26 20:28:45