2010-02-08 82 views
9

以編程方式選擇ListBox項目後,需要按下向上鍵兩次以移動選擇項。有什麼建議麼?在ListBox項目上設置焦點會中斷鍵盤導航

查看:

<ListBox Name="lbActions" Canvas.Left="10" Canvas.Top="10" 
       Width="260" Height="180"> 
     <ListBoxItem Name="Open" IsSelected="true" Content="Open"></ListBoxItem> 
     <ListBoxItem Name="Enter" Content="Enter"></ListBoxItem> 
     <ListBoxItem Name="Print" Content="Print"></ListBoxItem> 
</ListBox> 

代碼:

public View() 
{ 
    lbActions.Focus(); 
    lbActions.SelectedIndex = 0; //not helps 
    ((ListBoxItem) lbActions.SelectedItem).Focus(); //not helps either 
} 

回答

12

焦點不要設置到ListBox ...將焦點設置到選定的ListBoxItem的。這將解決「需要兩個鍵盤敲擊」的問題:

if (lbActions.SelectedItem != null) 
    ((ListBoxItem)lbActions.SelectedItem).Focus(); 
else 
    lbActions.Focus(); 

如果你的列表框包含的東西比ListBoxItem小號一樣,你可以用lbActions.ItemContainerGenerator.ContainerFromIndex(lbActions.SelectedIndex)獲得自動生成的ListBoxItem


如果您希望這期間窗口初始化發生,你需要把代碼中Loaded事件,而不是到構造。示例(XAML):

<Window ... Loaded="Window_Loaded"> 
    ... 
</Window> 

代碼(根據你的問題的例子):

private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
     lbActions.Focus(); 
     lbActions.SelectedIndex = 0; 
     ((ListBoxItem)lbActions.SelectedItem).Focus(); 
    } 
+0

我已經選擇的項目在XAML「IsSelected =」真「我提供了代碼的其他選擇,因此它可能是更明顯的是我想做的事情。」 lbActions.SelectedIndex = 0;「。 – StreamT 2010-02-08 18:46:55

+0

我的答案仍然有效,只需在* SelectedIndex = 0之後放置代碼* – Heinzi 2010-02-08 18:48:38

+0

不要爲我工作,選擇的項目,這不是問題,鍵盤導航後無法正常工作 – StreamT 2010-02-08 18:52:19

1

可以在XAML很容易地做到這一點。請注意,這隻會設置邏輯焦點。

例如:

<Grid FocusManager.FocusedElement="{Binding ElementName=itemlist, Path=SelectedItem}"> 
    <ListBox x:Name="itemlist" SelectedIndex="1"> 
     <ListBox.Items> 
      <ListBoxItem>One</ListBoxItem> 
      <ListBoxItem>Two</ListBoxItem> 
      <ListBoxItem>Three</ListBoxItem> 
      <ListBoxItem>Four</ListBoxItem> 
      <ListBoxItem>Five</ListBoxItem> 
      <ListBoxItem>Six</ListBoxItem> 
     </ListBox.Items> 
    </ListBox> 
</Grid>