How to identify which element was double clicked inside a ListBox?

前端 未结 1 717
挽巷
挽巷 2020-12-11 11:52

I have a listbox. The listbox DataTemplate consists of few Text Blocks and some TextBoxes.

The issue

相关标签:
1条回答
  • 2020-12-11 12:12

    You can use FrameworkTemplate.FindName Method (String, FrameworkElement) for this purpose and it should works as you want:

    private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(obj, i);
            if (child != null && child is childItem)
                return (childItem)child;
            childItem childOfChild = FindVisualChild<childItem>(child);
            if (childOfChild != null)
                return childOfChild;
        }
        return null;
    }
    

    Then:

    private void LstBox_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        ListBoxItem ListBoxItem = (ListBoxItem)(lstBox.ItemContainerGenerator.ContainerFromIndex(lstBox.SelectedIndex));
        ContentPresenter contentPresenter = FindVisualChild<ContentPresenter>(ListBoxItem);
        DataTemplate myDataTemplate = contentPresenter.ContentTemplate;
        StackPanel temp = (StackPanel)myDataTemplate.FindName("myStackPanel", contentPresenter);
        //*so as to do some further operations like make the textbox editable and so on* as you want
       (temp.FindName("field1TextBox") as TextBox).IsReadOnly = false;
    }
    

    Based on your question that you said: The listbox's DataTemplate consists of few TextBlock and some TextBoxes. (I assumed they are inside a StackPanel)

    0 讨论(0)
提交回复
热议问题