How do you programmatically set focus to the SelectedItem in a WPF ListBox that already has focus?
It's a couple lines of code. If you didn't want it in code-behind, I sure it could be packaged in a attached behaviour.
private void Button_Click(object sender, RoutedEventArgs e){ MainListBox.SelectedItem = MainListBox.Items[3]; MainListBox.UpdateLayout(); // Pre-generates item containers var listBoxItem = (ListBoxItem) MainListBox .ItemContainerGenerator .ContainerFromItem(MainListBox.SelectedItem); listBoxItem.Focus();}
Maybe with an attached behavior? Something like
public static DependencyProperty FocusWhenSelectedProperty = DependencyProperty.RegisterAttached( "FocusWhenSelected", typeof(bool), typeof(FocusWhenSelectedBehavior), new PropertyMetadata(false, new PropertyChangedCallback(OnFocusWhenSelectedChanged)));private static void OnFocusWhenSelectedChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { var i = (ListBoxItem)obj; if ((bool)args.NewValue) i.Selected += i_Selected; else i.Selected -= i_Selected; }static void i_Selected(object sender, RoutedEventArgs e){ ((ListBoxItem)sender).Focus();}
and in xaml
<Style TargetType="ListBoxItem"> <Setter Property="local:FocusWhenSelectedBehavior.FocusWhenSelected" Value="True"/> </Style>
You need only use ListBox.SelectedItem and then use ListBox.ScrollIntoView(listBox.SelectedItem)
Example code:
private void textBox2_TextChanged(object sender, TextChangedEventArgs e) { var comparision = StringComparison.InvariantCultureIgnoreCase; string myString = textBox2.Text; List<dynamic> index = listBox.Items.SourceCollection.OfType<dynamic>().Where(x=>x.Nombre.StartsWith(myString,comparision)).ToList(); if (index.Count > 0) { listBox.SelectedItem= index.First(); listBox.ScrollIntoView(listBox.SelectedItem); } }