我正在尝试将标准的WPF ListBox选定项(显示的)文本复制到剪贴板上,在按下CTRL+C键时。是否有简单的方法可以实现这一点?如果它适用于应用程序中的所有ListBox,那将是很好的。
提前致谢。
我正在尝试将标准的WPF ListBox选定项(显示的)文本复制到剪贴板上,在按下CTRL+C键时。是否有简单的方法可以实现这一点?如果它适用于应用程序中的所有ListBox,那将是很好的。
提前致谢。
由于您正在使用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));
}
}
}
}
<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 也可以不同,因此在实际项目中不能依赖它。