2010-02-08 12 views
9

ListBox öğesini program aracılığıyla seçtikten sonra, seçimi taşımak için iki kez tuşuna basmanız gerekir. Baska öneri?Odak Listesindeki bir öğenin ayarlanması klavye gezintisini bozuyor

Görünüm:

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

Kodu:

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

cevap

12

... ListBox odağı ayarlamak seçilen ListBoxItem odağı ayarlamayın. sizin ListBox ListBoxItem s'den daha başka bir şey içeriyorsa

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

, otomatik ListBoxItem oluşturulan almak için lbActions.ItemContainerGenerator.ContainerFromIndex(lbActions.SelectedIndex) kullanabilirsiniz: Bu "iki klavye vuruşları gerekli" sorunu çözecektir. Bu pencere başlatma sırasında olmak istiyorsanız


, sen Loaded olay yerine yapıcı içine kod yerleştirmeniz gerekir. Örnek (XAML): (sorunuzu örnek dayalı)

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

Kodu:

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

Zaten "IsSelected =" "ben ne yapmak istediğinizi daha belirgin olabilir bu yüzden, kodda ek bir seçim sağlamak" gerçek lbActions.SelectedIndex = XAML öğeyi seçtikten 0; " – StreamT

+0

Cevabım hala çalışıyor, sadece kodu * SelectedIndex = 0" dan sonra koyun. – Heinzi

+0

Benim için çalışmıyor. Öğe seçildi, bu sorun değil. Klavye gezinme düzgün çalışmıyor. – StreamT

1

Sen de XAML kolayca yapabilirsiniz. Lütfen bunun sadece mantıksal odağı ayarlayacağını unutmayın. Örneğin

:

<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> 
İlgili konular