What is the best way to add "copy to clipboard" functionality to a ListView control in WPF?
I tried adding an ApplicationCommands.Copy to either the ListView ContextMenu or the ListViewItem ContextMenu, but the command remains disabled.
Thanks, Peter
Here is an xaml sample of one of my attempts...
<Window.Resources>
<ContextMenu x:Key="SharedInstanceContextMenu" x:Shared="True">
<MenuItem Header="Copy" Command="ApplicationCommands.Copy"/>
</ContextMenu>
</Window.Resources>
<ListBox Margin="12,233,225,68" Name="listBox1" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=UpToSourceCategoryByCategoryId.Category}" ContextMenu="{DynamicResource ResourceKey=SharedInstanceContextMenu}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
How should I set the CommandTarget in this case?
Thanks,Peter
It looks like you need a CommandBinding.
Here is how I would probably go about doing what you trying to do.
<Window.CommandBindings>
<CommandBinding
Command="ApplicationCommands.Copy"
Executed="CopyCommandHandler"
CanExecute="CanCopyExecuteHandler" />
</Window.CommandBindings>
<Window.Resources>
<ContextMenu x:Key="SharedInstanceContextMenu">
<MenuItem Header="Copy" Command="ApplicationCommands.Copy"/>
</ContextMenu>
<Style x:Key="MyItemContainerStyle" TargetType="{x:Type ListBoxItem}">
<Setter Property="ContextMenu" Value="{StaticResource SharedInstanceContextMenu}" />
</Style>
</Window.Resources>
<ListBox ItemContainerStyle="{StaticResource MyItemContainerStyle}">
<ListBoxItem>One</ListBoxItem>
<ListBoxItem>Two</ListBoxItem>
<ListBoxItem>Three</ListBoxItem>
<ListBoxItem>Four</ListBoxItem>
</ListBox>
It is also possible to achieve this functionality via an attached property, as I described it on my blog. The idea is to register the ApplicationCommands.Copy command with the ListView and, when the command is executed, read the values from the data bindings.
You'll find a downloadable sample on the blog entry, too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With