Selecting a Textbox Item in a Listbox does not change the selected item of the listbox

后端 未结 15 1396
清酒与你
清酒与你 2020-11-27 04:10

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

15条回答
  •  一生所求
    2020-11-27 04:57

    Attached behavior based on Arcturus Answer to make it reuseable and to have it not hidden in the code behind.

    Create file with the attached behavior (= attached property)

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

    Add it to the resources of your liking.

    For example

    
        
    
    

    Add namespace

    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:

    
    

提交回复
热议问题