WPF列表框复制到剪贴板

17

我正在尝试将标准的WPF ListBox选定项(显示的)文本复制到剪贴板上,在按下CTRL+C键时。是否有简单的方法可以实现这一点?如果它适用于应用程序中的所有ListBox,那将是很好的。

提前致谢。


1
在 http://blogs.gerodev.com/post/Copy-Selected-Items-in-WPF-Listbox-to-Clipboard.aspx 找到了答案。但仍在寻找将其全局添加到应用程序的选项。 - Bhuvan
评论中的链接已失效。 - Ben Walker
@BenWalker.. 好吧,那是一个旧链接。下面eagleboost提供了相同的解决方案。 - Bhuvan
1个回答

25

由于您正在使用WPF,所以可以尝试使用附加行为


首先需要一个像这样的类:

public static class ListBoxBehaviour
{
    public static readonly DependencyProperty AutoCopyProperty = DependencyProperty.RegisterAttached("AutoCopy",
        typeof(bool), typeof(ListBoxBehaviour), new UIPropertyMetadata(AutoCopyChanged));

    public static bool GetAutoCopy(DependencyObject obj_)
    {
        return (bool) obj_.GetValue(AutoCopyProperty);
    }

    public static void SetAutoCopy(DependencyObject obj_, bool value_)
    {
        obj_.SetValue(AutoCopyProperty, value_);
    }

    private static void AutoCopyChanged(DependencyObject obj_, DependencyPropertyChangedEventArgs e_)
    {
        var listBox = obj_ as ListBox;
        if (listBox != null)
        {
            if ((bool)e_.NewValue)
            {
                ExecutedRoutedEventHandler handler =
                    (sender_, arg_) =>
                    {
                        if (listBox.SelectedItem != null)
                        {
                            //Copy what ever your want here
                            Clipboard.SetDataObject(listBox.SelectedItem.ToString());
                        }
                    };

                var command = new RoutedCommand("Copy", typeof (ListBox));
                command.InputGestures.Add(new KeyGesture(Key.C, ModifierKeys.Control, "Copy"));
                listBox.CommandBindings.Add(new CommandBinding(command, handler));
            }
        }
    }
}

然后您可以使用以下类似于XAML的代码:
<ListBox sample:ListBoxBehaviour.AutoCopy="True">
  <ListBox.Items>
    <ListBoxItem Content="a"/>
    <ListBoxItem Content="b"/>
  </ListBox.Items>
</ListBox>

更新:对于最简单的情况,您可以通过以下方式访问文本:
private static string GetListBoxItemText(ListBox listBox_, object item_)
{
  var listBoxItem = listBox_.ItemContainerGenerator.ContainerFromItem(item_)
                    as ListBoxItem;
  if (listBoxItem != null)
  {
    var textBlock = FindChild<TextBlock>(listBoxItem);
    if (textBlock != null)
    {
      return textBlock.Text;
    }
  }
  return null;
}

GetListBoxItemText(myListbox, myListbox.SelectedItem)
FindChild<T> is a function to find a child of type T of a DependencyObject

但是,就像 ListBoxItem 可以绑定到对象一样,ItemTemplate 也可以不同,因此在实际项目中不能依赖它。


感谢您提供这个优雅而几乎完美的解决方案。我想唯一缺失的部分是,在MVVM架构中,如何检测内容呈现器并获取实际显示的文本,因为我们不会绑定简单的字符串,而是对象。 - Bhuvan
我没有使用FindChild函数,而是使用了return listBoxItem.Content.ToString();代替return textBlock.Text; - Scott Hutchinson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接