ListBox中如何识别双击了哪个元素?我有一个列表框。列表框DataTemplate由几个文本块和一些文本框组成。问题是,在鼠标双击时,我需要找出完成双击的元素,以便进行一些进一步的操作,例如使TextBox可编辑等等。我还需要为列表双击定义一些操作。所以我不能单独处理每个组件的鼠标。所以我需要处理ListBox的鼠标并找出双击的元素。我尝试使用下面的代码,但它返回的是ListBox的名称而不是TextBox的名称:privatevoidmyListBox_OnPreviewMouseDoubleClick(objectsender,MouseButtonEventArgse){if(mouseWasDownOn!=null){stringelementName=mouseWasDownOn.Name;我也试过下面的问题WPFgetstheelementunderthemouseHowtoknowwhatcontrolthemouseclickedincanvas?获取WPF中鼠标下的逻辑UIElementwhile(!(targetisControl)&&(target!=null)){target=VisualTreeHelper.GetParent(target);但仍然找不到解决方案。所以请帮我通过双击获取元素类型或元素名称。您可以使用FrameworkTemplate.FindName方法(String,Fr??ameworkElement)来实现这一点,它应该按照您想要的方式工作:privatechildItemFindVisualChild(DependencyObjectobj)wherechildItem:DependencyObject{for(inti=0;i(child);if(childOfChild!=null)returnchildOfChild;}returnnull;}然后:privatevoidLstBox_OnPreviewMouseDoubleClick(objectsender,MouseButtonEventArgse){ListBoxItemListBoxItem=(ListBoxItem)(lstBox.ItemContainerGenerator.ContainerFromIndex(lstBox.SelectedIndex));ContentPresentercontentPresenter=Find(VisualChildListBoxItem);DataTemplatemyDataTemplate=contentPresenter.ContentTemplate;StackPaneltemp=(StackPanel)myDataTemplate.FindName("myStackPanel",contentPresenter);//*以便根据需要进行一些进一步的操作,例如使文本框可编辑等等*(temp.FindName("field1TextBox")asTextBox).IsReadOnly=false;}根据您所说的问题:列表框的DataTemplate包含一些TextBlocks和一些TextBoxes。(我还以为是在StackPanel里呢)以上是C#学习教程:如何识别ListBox中双击的是哪个元素?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
