c# - WPF上下文菜单,复制菜单项变灰

标签 c# .net wpf

我有一个 ListView 数据绑定(bind)到一个类的 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 中的选定文本。

我需要做什么才能让它发挥作用?覆盖我的类中绑定(bind)到 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

,这都有效

关于c# - WPF上下文菜单,复制菜单项变灰,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29111165/

相关文章:

c# WPF 更改 CheckBox 的复选颜色

c# - 使用自定义字段进行 Elasticsearch 的 Serilog 配置

c# - PInvoke 在类定义中不起作用

c# - 禁用按钮不会在服务器端触发点击事件

c# - ViewModel 类应该实现 INotifyPropertyChanged 还是我可以使用对象组合?

c# - MVVM:GUI 和 ViewModel 之间的真正分离

C#-从流中序列化/反序列化DES加密文件

.net - 使用Windows Runtime异步文件API来确保顺序文件访问?

.net - 如何将TCPClient和NetworkStream移植到Silverlight?

.net - 在 Windows 10 上构建 Windows 通用应用程序时遇到问题