【问题标题】:PreviewMouseDownEvent of Listbox blocking Command from Button来自 Button 的 Listbox 阻塞命令的 PreviewMouseDownEvent
【发布时间】:2023-03-11 15:11:01
【问题描述】:

在我的主视图中,我有一个Listbox,我为此设置了PreviewMouseLeftButtonDownEvent,我用它来支持拖放重新排序。

var style = ListBox.ItemContainerStyle;

style.Setters.Add(new Setter(AllowDropProperty, true));

style.Setters.Add(new EventSetter(PreviewMouseLeftButtonDownEvent, 
  new MouseButtonEventHandler(Input_Down)));

private void Input_Down(object sender, EventArgs e)
{
    if (!(sender is ListBoxItem))
       return;

    var draggedItem = sender as ListBoxItem;

    isDragging = true;
    StartDrag(draggedItem);
}

private void StartDrag(ListBoxItem draggedItem)
{
    draggedItem.IsSelected = true;
    DragDrop.DoDragDrop(draggedItem, draggedItem.DataContext, DragDropEffects.Move);

}

ListBox.ItemTemplate 中有一个带有更新命令的按钮:

    <Button Command="{Binding Path=UpdateCommand}" Content="Button"/>

但是,当我设置PreviewMouseLeftButtonDownEvent 时,该命令从未被触发。如果我删除 PreviewMouseLeftButtonDownEvent 设置器,该命令可以正常工作。关于为什么会这样以及如何同时使用这两种方法的任何想法?

【问题讨论】:

  • 您是否在您的Input_Down 方法中将e.Handled 设置为true
  • 没有,我基本上只是开始拖拽操作
  • 你能贴出Input_Down方法的代码吗?
  • 我更新了问题
  • 问题是DoDragDrop中断Click进程。试试&lt;Button ... ClickMode="Press"/&gt; 是否有帮助,但这意味着点击会立即出现在按下而不是发布时

标签: c# wpf events listbox command


【解决方案1】:

DragDrop.doDragDrop() 操作似乎阻止了所有底层事件,这意味着来自被单击按钮的命令不会被触发。

由于我没有找到任何干净的方法,所以我决定进行 hack。在 ListBox.ItemContainerStyle 的事件处理程序中,我检查 RoutedEventArgs 中的原始源是否是附有 ICommand 的 Button。如果是这样,我会中止 DragDrop.doDragDrop() 过程:

style.Setters.Add(new EventSetter(PreviewMouseLeftButtonDownEvent, 
  new MouseButtonEventHandler(Input_Down)));

private void Input_Down(object sender, RoutedEventArgs e)
{
    if (EventTriggeredByButtonWithCommand(e))
        return;

    var draggedItem = sender as FrameworkElement;

    if(draggedItem !=null)
        StartDrag(draggedItem);

}
bool EventTriggeredByButtonWithCommand(RoutedEventArgs e)
{
    var frameWorkElement = e.OriginalSource as FrameworkElement;

    if (frameWorkElement == null) 
        return false;

    var button = frameWorkElement.TemplatedParent as Button;

    if (button == null) 
        return false;

    return button.Command != null;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多