2010-10-14 101 views
10

我想复制一个标准的WPF列表框选择项目(显示)文本到CTRL + C上的剪贴板。有没有简单的方法来实现这一点。如果这是适用于所有列表框的东西int他的应用程序..这将是伟大的。WPF listbox复制到剪贴板

在此先感谢。

+1

在http://blogs.gerodev.com/post/Copy-Selected-Items-in-WPF-Listbox-to-Clipboard.aspx找到答案。但仍在寻找一个选项来将其全局添加到应用程序中。 – Bhuvan 2010-10-14 22:16:39

+0

以上链接发表评论已无效。 – 2013-10-16 18:11:36

+0

@BenWalker ..那是一个旧的链接。同样的解决方案由eagleboost提供 – Bhuvan 2013-10-16 21:52:24

回答

18

正如你在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也可以不同,所以你不能依赖它在真实的项目中。

+0

感谢这款优雅且几乎完美的解决方案。我猜想唯一缺少的部分就是如何检测内容展示器并获取实际显示的文本,以防MVVM架构,因为我们不会绑定简单的字符串,而是绑定对象。 – Bhuvan 2010-10-18 18:15:42