我有一个 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/