2010-06-03 75 views
2

我這樣一個文本框設置焦點:WPF文本框對焦

<DockPanel 
     Margin="0,0,0,0" 
     LastChildFill="True" 
     FocusManager.FocusedElement="{Binding ElementName=messengerTextToSend}"> 
     <ListBox 
      x:Name="messengerLabelParticipants" 
      DockPanel.Dock="Top" Height="79" Margin="0,1,0,0" Padding="0" 
      Background="{x:Null}" BorderBrush="{x:Null}" BorderThickness="0" 
      AllowDrop="True" 
      ItemsSource="{Binding Path=involvedUsers}" ItemTemplate="{StaticResource chatParticipants}" Tag="{Binding Path=chatSessionID}" 
      Drop="participantList_Drop" DragEnter="participantList_DragEnter" DragLeave="messengerLabelParticipants_DragLeave"> 
     </ListBox> 
     <TextBox 
      x:Name="messengerTextToSend" 
      Focusable="True" 
      Margin="10,0,10,10" 
      DockPanel.Dock="Bottom" Height="100" 
      Tag="{Binding Path=.}" 
      KeyUp="messengerTextToSend_KeyUp" 
      Cursor="IBeam" 
      Style="{StaticResource messengerTextBoxSendText}"/> 
     <ScrollViewer 
      x:Name="messengerScroller" 
      Template="{DynamicResource ScrollViewerControlTemplate1}" 
      ScrollChanged="messengerScroller_ScrollChanged" Loaded="messengerScroller_Loaded" 
      Margin="0,10,0,10"> 
      <ListBox 
       x:Name="messengerListMessages" 
       Margin="10,0,0,0" Padding="0" 
       Background="{x:Null}" BorderBrush="{x:Null}" BorderThickness="0" 
       IsSynchronizedWithCurrentItem="True" 
       ItemsSource="{Binding Path=messages}" ItemTemplateSelector="{StaticResource messageTemplateSelector}"> 
      </ListBox> 
     </ScrollViewer> 
    </DockPanel> 

然而,當頁面加載,雖然文本框在視覺上顯得有重點,光標是靜態的,我必須手動要麼點擊在文本框或選項卡上以便開始輸入。我不確定我做錯了什麼,但我已經嘗試了所有設置,並將其設置在代碼中以使其正常工作。任何援助將不勝感激。

回答

3

將FocusManager.FocusedElement命令移動到Window元素。

<Window x:Class="MYClass.Views.MainView" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="My Window" 
    FocusManager.FocusedElement="{Binding ElementName=messengerTextToSend}"> 
    Height="400" 
    Width="600"> 
    <DockPanel> 
    </DockPanel> 
</Window> 

查看此question爲用戶控件的情況。

+0

謝謝,代碼在一個窗口內的用戶控件中。我曾嘗試將其添加到UserControl,但這會導致TextBox未被設置爲以任何方式聚焦。 – Jezz 2010-06-03 14:05:05

+0

在Stackoverlfow中查看問題:673536,並在DockPanel中將IsFocusScope設置爲true。 FocusManager.IsFocusScope =「True」 – Zamboni 2010-06-03 14:51:03

+0

需要創建特定的事件處理程序 private void messengerTextToSend_Loaded(object sender,RoutedEventArgs e) messengerTextToSend.Focus(); } 現在工作正常,感謝你的幫助。 – Jezz 2010-06-03 15:22:59