WPF右键菜单,复制菜单项变灰

6

我有一个ListView,数据绑定到一个类的ObservableCollection上。我想在ListView中添加一个“复制”菜单项,代码如下:

    <ListView.ContextMenu>
        <ContextMenu>
            <MenuItem Command="{x:Static ApplicationCommands.Copy}"></MenuItem>
            <MenuItem Command="{x:Static ApplicationCommands.Copy}"
                      CommandTarget="{Binding Path=PlacementTarget, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"></MenuItem>
        </ContextMenu>
    </ListView.ContextMenu>

现在当我右键单击菜单项时,菜单会弹出但是复制选项是灰色的。我的猜测是它认为没有内容可以复制,但这并没有意义,因为当我右键单击列表框项时,技术上我正选择某些内容以供复制,而此时列表框项已被选中。我只希望它复制ListView中所选的文本。
我该怎么做才能使它工作?覆盖绑定到Listview的类中的复制类吗?我试过谷歌搜索,但并没有什么进展。
2个回答

3
我刚刚为自己整理了一个示例,内容如下:

<Window.CommandBindings>
    <CommandBinding
        Command="ApplicationCommands.Copy"
        CanExecute="CommandBinding_CanExecute"
        Executed="CommandBinding_Executed"/>
</Window.CommandBindings>


<Window.Resources>
    <ContextMenu x:Key="MyContextMenu">
        <MenuItem Header="Copy" Command="ApplicationCommands.Copy"/>
    </ContextMenu>

    <Style x:Key="MyItemContainerStyle" TargetType="{x:Type ListViewItem}">
        <Setter Property="ContextMenu" Value="{StaticResource MyContextMenu}" />
    </Style>
</Window.Resources>

<Grid>
    <ListView x:Name="MyListView" ItemContainerStyle="{StaticResource MyItemContainerStyle}"/>                  
</Grid>

然后在代码后台:

// Test class with a single string property
private class MyData
{
    public String Name { get; set; }

    public MyData(String name)
    {
        Name = name;
    }

    public override string ToString()
    {
        return Name;
    }
}

public MainWindow()
{
    InitializeComponent();

    // Create some test data
    ObservableCollection<MyData> names = new ObservableCollection<MyData>();
    names.Add(new MyData("Name 1"));
    names.Add(new MyData("Name 2"));
    names.Add(new MyData("Name 3"));
    MyListView.ItemsSource = names;
}

private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = true;
}

private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
   Clipboard.SetText(MyListView.SelectedItem.ToString());
}

无论您是从上下文菜单中选择“复制”,还是使用“Ctrl+C”,都可以使用此功能。

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接