Jam*_*add 3 wpf listbox mouseevent elementflow
我想在用户单击任何给定ListBox项目时运行一些代码.我的设置是一个ListBox自定义ItemsPanelTemplate(Pavan的ElementFlow).根据进入的位置数据,MouseLeftButtonDown有没有办法告诉哪个项目被点击了?习惯使这变得更加困难(或更令人困惑)ItemsPanelTemplate.
dec*_*jau 12
你可以有一个ItemContainerStyle,并在其中指定一个EventSetter:
<ListBox>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<EventSetter Event="MouseLeftButtonDown" Handler="ListBoxItem_MouseLeftButtonDown" />
...
Run Code Online (Sandbox Code Playgroud)
然后,在MouseLeftButtonDown的处理程序中,"sender"将是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;
}
Run Code Online (Sandbox Code Playgroud)