Listbox的PreviewMouseDownEvent阻止来自Button的命令

时间:2013-07-20 14:07:56

标签: c# wpf events listbox command

在我的主视图中,我有一个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时,永远不会触发该命令。如果我删除{{1}} setter,该命令工作正常。关于为什么会这样做以及如何使用它们的任何想法?

1 个答案:

答案 0 :(得分:0)

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;
}