Come sei in WPF così si potrebbe provare i comportamenti collegati
In primo luogo è necessaria una classe come questa:
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));
}
}
}
}
Allora avete la XAML come questo
<ListBox sample:ListBoxBehaviour.AutoCopy="True">
<ListBox.Items>
<ListBoxItem Content="a"/>
<ListBoxItem Content="b"/>
</ListBox.Items>
</ListBox>
Aggiornamenti: per il caso più semplice, è possibile accedere al testo nel modo seguente:
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
Ma proprio come il ListBoxItem potrebbe essere legato di opporsi, ItemTemplate potrebbe essere diverso e, quindi non si può fare affidamento su di essa in progetti reali.
Trovato la risposta su http://blogs.gerodev.com/post/Copy-Selected-Items-in-WPF-Listbox-to-Clipboard.aspx. Ma ancora alla ricerca di un'opzione per aggiungerla globalmente all'app. – Bhuvan
Il link sopra nel commento è morto. –
@ BenWalker .. beh quello era un vecchio link. La stessa soluzione è fornita di seguito da eagleboost – Bhuvan