2010-10-14 100 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