gpt4 book ai didi

c# - 如何识别在 ListBox 中双击了哪个元素?

转载 作者:太空宇宙 更新时间:2023-11-03 12:45:40 27 4
gpt4 key购买 nike

我有一个列表框listbox DataTemplate 由几个 Text Blocks 和一些 TextBoxes 组成。

问题出在鼠标双击上 我需要找出双击是在哪个元素上完成的,以便进行一些进一步的操作,例如使 TextBox 可编辑等等。同时我还需要为列表双击定义一些 Action 。所以我无法为每个组件单独处理鼠标按下。

因此,我需要处理 ListBox 的鼠标向下操作,并找出双击的是哪个元素。

我尝试使用下面的代码,但它返回的是 ListBoxName 而不是 TextBoxName :

private void myListBox_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
var mouseWasDownOn = e.Source as FrameworkElement;
if (mouseWasDownOn != null)
{
string elementName = mouseWasDownOn.Name;
}
}

我也尝试过以下问题

WPF Get Element(s) under mouse

How to know what control the mouse has clicked in a canvas?

Getting the Logical UIElement under the mouse in WPF

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

然后:

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

根据你说的问题:listboxDataTemplate 由几个 TextBlock 和一些 TextBoxes 组成。 (我假设它们在 StackPanel 中)

关于c# - 如何识别在 ListBox 中双击了哪个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37404061/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com