【问题标题】:WPF listbox copy to clipboardWPF 列表框复制到剪贴板
【发布时间】:2010-10-14 20:53:22
【问题描述】:

我正在尝试将标准 WPF 列表框选定项(显示)文本复制到 CTRL+C 上的剪贴板。有什么简单的方法可以实现这一点。如果它适用于他的应用程序中的所有列表框......那就太好了。

提前致谢。

【问题讨论】:

  • blogs.gerodev.com/post/… 找到了答案。但仍在寻找将其全局添加到应用程序的选项。
  • 评论中的上述链接已失效。
  • @BenWalker .. 那是一个旧链接。 eagleboost 下面提供了相同的解决方案

标签: c# wpf listbox clipboard


【解决方案1】:

因为您在 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 架构的情况下,如何检测内容呈现器并获取实际显示的文本,因为我们不会绑定简单的字符串,而是对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-10
  • 2020-02-06
  • 1970-01-01
  • 2012-12-02
  • 1970-01-01
  • 1970-01-01
  • 2011-06-21
相关资源
最近更新 更多