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

后端 未结 15 1422
清酒与你
清酒与你 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 05:01

    Old discussion, but maybe my answer helps others....

    Ben's solution has the same problem as Grazer's solution. The bad thing is that the selection depends on the [keyboard] focus of the textbox. If you have another control on your dialog (i.e. a button) the focus gets lost when clicking the button and the listboxitem becomes un-selected (SelectedItem == null). So you have different behavior for clicking the item (outside the textbox) and clicking in the textbox. This is very tedious to handle and looks very strange.

    I'm quite sure there is no pure XAML solution for this. We need code-behind for this. The solution is close to what Mark suggested.

    (in my example I use ListViewItem instead of ListBoxItem, but the solution works for both).

    Code-behind:

    private void Element_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            var frameworkElement = sender as FrameworkElement;
            if (frameworkElement != null)
            {
                var item = FindParent(frameworkElement);
                if (item != null)
                    item.IsSelected = true;
            }
        }
    

    with FindParent (taken from http://www.infragistics.com/community/blogs/blagunas/archive/2013/05/29/find-the-parent-control-of-a-specific-type-in-wpf-and-silverlight.aspx ):

    public static T FindParent(DependencyObject child) where T : DependencyObject
        {
            //get parent item
            DependencyObject parentObject = VisualTreeHelper.GetParent(child);
    
            //we've reached the end of the tree
            if (parentObject == null) return null;
    
            //check if the parent matches the type we're looking for
            T parent = parentObject as T;
            if (parent != null)
                return parent;
    
            return FindParent(parentObject);
        }
    

    In my DataTemplate:

    
    

提交回复
热议问题