【问题标题】:Select ListBoxItem on MouseUp WPF在 MouseUp WPF 上选择 ListBoxItem
【发布时间】:2012-06-11 21:54:09
【问题描述】:

我有一个可以多选的 ListBox。我正在其中进行拖放操作。我使用 Ctrl+A 选择所有项目。但是,一旦我单击一个项目开始拖动,项目就会被取消选择。有没有办法在鼠标上选择/取消选择列表框项。

【问题讨论】:

    标签: wpf listbox mouse


    【解决方案1】:

    ListBoxItem 覆盖它的 OnMouseLeftButtonDown 并调用包含 ListBox 的方法来处理选择。因此,如果您想将鼠标放在选定的列表框项目上并启动拖动,则需要在 ListBoxItem 上发生这种情况之前开始拖动。因此,您可以尝试处理 ListBox 上的 PreviewMouseLeftButtonDown 并检查 e.OriginalSource。如果那是 ListBoxItem 或列表框项中的元素(您需要沿着可视树向上走),那么您可以启动拖动操作。例如

    private void OnPreviewLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        var source = e.OriginalSource as DependencyObject;
    
        while (source is ContentElement)
            source = LogicalTreeHelper.GetParent(source);
    
        while (source != null && !(source is ListBoxItem))
            source = VisualTreeHelper.GetParent(source);
    
        var lbi = source as ListBoxItem;
    
        if (lbi != null && lbi.IsSelected)
        {
            var lb = ItemsControl.ItemsControlFromItemContainer(lbi);
            e.Handled = true;
            DragDrop.DoDragDrop(....);
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-12
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多