[英]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.