wpf - 从 MouseLeftButtonDown 获取 WPF ListBox 项

标签 wpf listbox mouseevent elementflow

当用户单击任何给定的 ListBox 时,我想运行一些代码元素。我的设置是 ListBox带定制ItemsPanelTemplate (Pavan 的 ElementFlow)。基于进入 MouseLeftButtonDown 的位置数据有没有办法知道点击了哪个项目?自定义 ItemsPanelTemplate 使这变得更加困难(或更令人困惑)。 .

最佳答案

您可以拥有一个 ItemContainerStyle,并在其中指定一个 EventSetter:

<ListBox>
    <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <EventSetter Event="MouseLeftButtonDown" Handler="ListBoxItem_MouseLeftButtonDown" />
    ...

然后,在 MouseLeftButtonDown 的处理程序中,“发送者”将是 ListBoxItem。

另外,如果你不想使用这个方法,你可以调用 HitTest 来找出指定位置的 Visual 对象:
HitTestResult result = VisualTreeHelper.HitTest(myCanvas, pt);

ListBoxItem lbi = FindParent<ListBoxItem>( result.VisualHit );

public static T FindParent<T>(DependencyObject from) 
    where T : class
{
    T result = null;
    DependencyObject parent = VisualTreeHelper.GetParent(from);

    if (parent is T)
       result = parent as T;
    else if (parent != null)
       result = FindParent<T>(parent);

    return result;
}

关于wpf - 从 MouseLeftButtonDown 获取 WPF ListBox 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1335745/

相关文章:

wpf - 以编程方式将 Datagrid 行显示在 WPF、MVVM 中

c# - 使用 Entity Framework 进行 LIKE 查询

c# - 无法按名称从 C# 中的列表框中删除 StackPanel

c# - SelectedIndex 第一次调用时列表框 SelectedValue 错误

wpf - 自定义样式列表框 - 如何保留所选项目的样式?

java - 如何使用 Robot 类触发组件上的单击事件?

javascript - 可点击的敌人

c# - WPF XAML 解析异常发生错误?

java - 判断是否按下了鼠标中键而不是alt键

c# - 在 WPF 程序中,我想更改 "Lines"上所有 "Canvas"的描边颜色