繁体   English   中英

WPF上下文菜单,复制菜单项显示为灰色

[英]WPF Context Menu, Copy Menu Item is grayed out

我有一个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的副本类? 我试着谷歌搜索,但没有走得太远。

我刚刚总结了一个适合我的例子:

<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());
}

无论您是从上下文菜单中选择“ Copy ”,还是使用Ctrl+C

在没有重写所有内容的情况下,关于Gary的示例需要注意的是CanExecute语句的存在,它控制命令的启用/禁用。 您应该更多地查看正确的命令结构,因为我认为您错过了命令的真正威力。

https://msdn.microsoft.com/en-us/library/ms753200%28v=vs.110%29.aspx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM