Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy Context Menu for ListView Control

Tags:

wpf

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

like image 218
user34403 Avatar asked Nov 04 '08 20:11

user34403


2 Answers

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>
like image 129
Todd White Avatar answered Nov 04 '22 09:11

Todd White


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.

like image 1
jannmueller Avatar answered Nov 04 '22 08:11

jannmueller