public class ItemDoubleClickBehavior : Behavior<ListBox>
{
#region Properties
MouseButtonEventHandler Handler;
#endregion
#region Methods
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.PreviewMouseDoubleClick += Handler = (s, e) =>
{
e.Handled = true;
if (!(e.OriginalSource is DependencyObject source)) return;
ListBoxItem sourceItem = source is ListBoxItem ? (ListBoxItem)source :
source.FindParent<ListBoxItem>();
if (sourceItem == null) return;
foreach (var binding in AssociatedObject.InputBindings.OfType<MouseBinding>())
{
if (binding.MouseAction != MouseAction.LeftDoubleClick) continue;
ICommand command = binding.Command;
object parameter = binding.CommandParameter;
if (command.CanExecute(parameter))
command.Execute(parameter);
}
};
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.PreviewMouseDoubleClick -= Handler;
}
#endregion
}
下面是用于查找父对象的扩展类。
public static class UIHelper
{
public static T FindParent<T>(this DependencyObject child, bool debug = false) where T : DependencyObject
{
DependencyObject parentObject = VisualTreeHelper.GetParent(child);
//we've reached the end of the tree
if (parentObject == null) return null;
//check if the parent matches the type we're looking for
if (parentObject is T parent)
return parent;
else
return FindParent<T>(parentObject);
}
}
5条答案
按热度按时间qcbq4gxm1#
您可以将样式添加到ListBox.ItemContainerStyle,然后在此处添加EventSetter:
ListBoxItem_MouseDoubleClick是代码隐藏中的一个方法,具有MouseDoubleClick的正确签名。
a6b3iqyw2#
我想解决这个问题,而不需要在代码隐藏中处理listBoxItem双击事件,并且我不想覆盖listBoxItem样式(或首先定义要覆盖的样式),我只想在双击listBox时触发一个命令。
我创建了一个附加属性,如下所示(代码非常具体,但您可以根据需要将其概括):
然后,我使用attached属性和目标命令声明ListBox:
希望这个有用。
hk8txs483#
我已经更新了AndrewS解决方案,以解决双击列表框中的任何位置时执行命令的问题:
在XAML中,ListBox的声明为:
ztmd8pv54#
我使用的是表达式SDK 4.0
海米尔湾
toe950275#
这里有一个在
ListBox
和ListView
上都能实现的行为。这是基于Andrew S.和Vadim Tofan的回答,他们做得很好!下面是用于查找父对象的扩展类。
用法: