Như bạn đang ở trong WPF, do đó bạn có thể thử các hành vi gắn
Trước tiên, bạn cần một lớp học như thế này:
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));
}
}
}
}
Sau đó, bạn có XAML như thế này
<ListBox sample:ListBoxBehaviour.AutoCopy="True">
<ListBox.Items>
<ListBoxItem Content="a"/>
<ListBoxItem Content="b"/>
</ListBox.Items>
</ListBox>
Cập nhật: Đối với trường hợp đơn giản nhất, bạn có thể truy cập văn bản theo cách sau:
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
Nhưng cũng giống như ListBoxItem có thể bị ràng buộc đối tượng, ItemTemplate cũng có thể khác nhau, vì vậy bạn không thể dựa vào nó trong các dự án thực.
Tìm thấy câu trả lời tại http://blogs.gerodev.com/post/Copy-Selected-Items-in-WPF-Listbox-to-Clipboard.aspx. Nhưng vẫn đang tìm kiếm một tùy chọn để thêm nó trên toàn cầu vào ứng dụng. – Bhuvan
Trên liên kết trong bình luận đã chết. –
@BenWalker .. đó là một liên kết cũ. Cùng một giải pháp được cung cấp dưới đây bởi eagleboost – Bhuvan