如何识别在ListBox中双击哪个元素?
我有一个listbox
。 listbox
DataTemplate
由几个Text Blocks
和一些TextBoxes
。
问题是鼠标双击我需要找出双击完成的元素,以便做一些进一步的操作,如使TextBox
可编辑等等。 同时我还需要为列表双击定义一些动作。 所以我无法单独处理每个组件的鼠标。
因此,我需要为ListBox
处理鼠标,并找出双击所在的元素。
我尝试使用下面的代码,但它返回ListBox
的Name
而不是TextBox
的Name
:
private void myListBox_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e) { var mouseWasDownOn = e.Source as FrameworkElement; if (mouseWasDownOn != null) { string elementName = mouseWasDownOn.Name; } }
我也按照以下问题尝试过
WPF在鼠标下获取元素
如何知道鼠标在canvas中点击了什么控件?
在WPF中获取鼠标下的逻辑UIElement
public void ListBox_MouseDownHandler(object sender, MouseButtonEventArgs e) { HitTestResult target = VisualTreeHelper.HitTest(myListBoxName, e.GetPosition(myListBoxName)); while(!(target is Control) && (target != null)) { target = VisualTreeHelper.GetParent(target); } }
但仍无法找到解决方案。 因此,请帮助我从双击中获取元素类型或元素名称。
您可以使用FrameworkTemplate.FindName Method (String, FrameworkElement)
来实现此目的,它应该可以按您的方式工作:
private childItem FindVisualChild(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 (child); if (childOfChild != null) return childOfChild; } return null; }
然后:
private void LstBox_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e) { ListBoxItem ListBoxItem = (ListBoxItem)(lstBox.ItemContainerGenerator.ContainerFromIndex(lstBox.SelectedIndex)); ContentPresenter contentPresenter = FindVisualChild(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; }
基于您所说的问题: listbox
的DataTemplate
包含少量TextBlock
和一些TextBoxes
。 (我以为它们在StackPanel
)