private static void HandleItemLeftMouseUp(object sender, MouseButtonEventArgs eventArgs) { eventArgs.Handled = false; if (eventArgs.OriginalSource is TextBox) { ListBoxItem textBoxParentItem; ListBox textBoxParentItemsControl; if (TextBoxFocusAttachedBehavior.TryFindAttachedElementsParentItem( eventArgs.OriginalSource as DependencyObject, out textBoxParentItem) && TextBoxFocusAttachedBehavior.TryFindAttachedElementsParentItemsControl( eventArgs.OriginalSource as DependencyObject, out textBoxParentItemsControl)) { textBoxParentItemsControl.SelectedItem = textBoxParentItem.Content; } return; } // Apply behavior when ListBoxItem is clicked anywhere else but Buttons, Checkboxes, etc if (eventArgs.OriginalSource is Border) { var parentItem = sender as ListBoxItem; TextBox textBox = TextBoxFocusAttachedBehavior.GetParentItemTextBox(parentItem); TextBoxFocusAttachedBehavior.ApplyBehaviors(textBox); } }
/// <summary> /// Listen to the parent ListBoxItem's PreviewMouseLeftButtonUp to handle focus behavior. <para/> /// Using the Selected event or in general the default ListBox selection mechanism <para/> /// would interfere with other user input (e.g. opening context menu, which involves <para/> /// the corresponding item to be selected. So stealing the focus in such case leads to odd behavior.) /// </summary> /// <param name="attachingElement"></param> /// <param name="isEnabled"></param> private static void ObserveAttachedElement(DependencyObject attachingElement, bool isEnabled) { ListBox itemsControl; if (TextBoxFocusAttachedBehavior.TryFindAttachedElementsParentItemsControl(attachingElement, out itemsControl)) { ListBoxItem item; if (TextBoxFocusAttachedBehavior.TryFindAttachedElementsParentItem(attachingElement, out item)) { if (isEnabled) { // Ensure to listen to event with only one handler assigned each ItemsControl if (!TextBoxFocusAttachedBehavior.GetAttachedElementIsRegistered(itemsControl)) { //LogDocumentKeyboardInputHandler.Navigated += TextBoxFocusAttachedBehavior.HandleFocusOnKeyboardNavigated; } // Store the item's attached TextBox for later use with the event handlers TextBoxFocusAttachedBehavior.SetParentItemTextBox(item, attachingElement as TextBox); WeakEventManager <UIElement, MouseButtonEventArgs> .AddHandler( item, "PreviewMouseLeftButtonUp", TextBoxFocusAttachedBehavior.HandleItemLeftMouseUp); TextBoxFocusAttachedBehavior.SetAttachedElementIsRegistered(item, true); } else { //LogDocumentKeyboardInputHandler.Navigated -= TextBoxFocusAttachedBehavior.HandleFocusOnKeyboardNavigated; // Release the attached TextBox TextBoxFocusAttachedBehavior.SetParentItemTextBox(item, null); WeakEventManager <UIElement, MouseButtonEventArgs> .RemoveHandler( item, "PreviewMouseLeftButtonUp", TextBoxFocusAttachedBehavior.HandleItemLeftMouseUp); TextBoxFocusAttachedBehavior.SetAttachedElementIsRegistered(item, false); } } } }