I Have a wpf Listbox that display\'s a list of textboxes. When I click on the Textbox the Listbox selection does not change. I have to click next to the TextBox to select th
Attached behavior based on Arcturus Answer to make it reuseable and to have it not hidden in the code behind.
public static class SelectListBoxItemWhenControlInsideTheItemIsClickedBehavior
{
public static readonly DependencyProperty EnableProperty = DependencyProperty.RegisterAttached(
"Enable",
typeof(bool),
typeof(SelectListBoxItemWhenControlInsideTheItemIsClickedBehavior),
new FrameworkPropertyMetadata(false, OnEnableChanged));
public static bool GetEnable(FrameworkElement frameworkElement)
{
return (bool)frameworkElement.GetValue(EnableProperty);
}
public static void SetEnable(FrameworkElement frameworkElement, bool value)
{
frameworkElement.SetValue(EnableProperty, value);
}
private static void OnEnableChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if ( d is ListBoxItem listBoxItem)
listBoxItem.PreviewGotKeyboardFocus += ListBoxItem_PreviewGotKeyboardFocus;
}
private static void ListBoxItem_PreviewGotKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e)
{
var listBoxItem = (ListBoxItem)sender;
listBoxItem.IsSelected = true;
}
}
For example
if visual studio is not clever enough to add it automatically. for example when your project is called "MyApp" and you saved the file in the Folder "MyBehaviors", the Namespace would be under Window: