我有一個WPF應用程序了其中MainWindow類具有<Window.CommandBindings>
和<Window.InputBindings>
所以可以檢測CTRL + X,CTRL + Ç和CTRL + V命令。CTRL + C
的主窗口包含一個DataGrid,我想選擇一個行,該行與CTRL +ç命令複製數據。當在DataGrid中選擇一行時,CTRL + C命令在MainWindow中不再被檢測到。 CTRL + X and CTRL + V仍然被檢測到。
我設法通過一個非常簡單的例子重現了這個問題。只需複製並粘貼下面的代碼,它應該在旅途中編譯和運行。然後執行以下操作:
- 連按CTRL +X,CTRL +ç或 CTRL +V:彈出窗口會說被激活什麼命令。
- 在DataGrid中選擇一行,然後按CTRL + C:什麼都不會發生。
- CTRL + X或CTRL + V將仍然被檢測到。
MainWindow.XAML代碼
<!-- Commands for hot keys -->
<Window.CommandBindings>
<!-- Source -->
<!-- http://stackoverflow.com/questions/4682915/defining-menuitem-shortcuts -->
<CommandBinding Command="Cut" Executed="btnCut_Click" />
<CommandBinding Command="Copy" Executed="btnCopy_Click" />
<CommandBinding Command="Paste" Executed="btnPaste_Click" />
</Window.CommandBindings>
<!-- Hot keys -->
<Window.InputBindings>
<KeyBinding Key="X" Modifiers="Control" Command="Cut" />
<KeyBinding Key="C" Modifiers="Control" Command="Copy" />
<KeyBinding Key="V" Modifiers="Control" Command="Paste" />
</Window.InputBindings>
<Grid>
<DataGrid Name="dgPersons" HorizontalScrollBarVisibility="Auto" AutoGenerateColumns="False" IsReadOnly="True" SelectionMode="Extended" GridLinesVisibility="None" Background="White" Margin="75,59,35,104">
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="BorderThickness" Value="0" />
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
</Style>
</DataGrid.CellStyle>
<DataGrid.Columns>
<!-- Name -->
<DataGridTextColumn Header="Name" Width="100" Binding="{Binding Name, Mode=OneTime}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
MainWindow.cs代碼
public partial class MainWindow : Window
{
ObservableCollection<Person> persons = new ObservableCollection<Person>();
public MainWindow()
{
InitializeComponent();
Person person1 = new Person("Person1");
Person person2 = new Person("Person2");
Person person3 = new Person("Person3");
persons.Add(person1);
persons.Add(person2);
persons.Add(person3);
dgPersons.ItemsSource = persons;
}
private void btnCut_Click(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("CUT command activated");
}
private void btnCopy_Click(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("COPY command activated");
}
private void btnPaste_Click(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("PASTE command activated");
}
}
public class Person
{
string name;
public Person(string name)
{
this.name = name;
}
public string Name
{
get { return name; }
}
}
如何獲得CTRL +C在DataGrid中選擇一行時工作?
1. http://stackoverflow.com/questions/832185/how-to-detect-when-a-hotkey-shortcut-key-is-pressed 2. http://stackoverflow.com/questions/1361350/鍵盤快捷鍵功能於WPF – 2014-10-10 06:27:01
請點擊此鏈接 http://stackoverflow.com/questions/13876874/wpf-datagrid-copy-to-clipboard-after-ctrlc-oncopyingrowclipboardcontent – daniele3004 2014-10-10 07:06:54
'Ctr' +' C'由'DataGrid'本身處理,請參閱[this](http://stackoverflow.com/q/12941707/1997232)問題以獲得創建行爲的解決方法。也許更簡單的方法是使用熱鍵,這些熱鍵不被控件使用,例如'Alt' +'C'。 – Sinatr 2014-10-10 08:37:34