【问题标题】:How to identify which element was double clicked inside a ListBox?如何识别在 ListBox 中双击了哪个元素?
【发布时间】:2016-07-23 19:58:54
【问题描述】:

我有一个listboxlistbox DataTemplate 由少数Text Blocks 和一些TextBoxes 组成。

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

因此,我需要为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);
    }
}

但仍然找不到解决方案。因此,请帮助我通过双击获取元素类型或元素名称。

【问题讨论】:

  • 是否可以使用ItemTemplate?
  • 哦,你是想说,如果我在后面的代码中处理数据模板的双击事件,我可以获得元素类型或名称吗?
  • 你能展示你的 XAML 代码吗?
  • 正如@S.Akbari 所说,您需要向我们展示您的 XAML 代码。但在我的脑海中,你可以使用 Style.Triggers->EventTrigger->BeginStoryboard-> Animate IsReadOnly 在离散步骤中设置为 false,如果这就是你所需要的

标签: c# .net wpf listbox


【解决方案1】:

您可以为此目的使用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 内)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多