在WPF中给控件添加键盘命令如复制、粘贴等,与WinForm有所不同,下面以给ListView添加Ctrl+C复制命令为例说明:
<ListView x:Name="lvEntries" ItemsSource="{Binding Path=Card.CardEntries}" SelectedItem="{Binding Path=Card.CardEntry}" Margin="0,0,5,0" SelectionMode="Single" >
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<EventSetter Event="MouseDoubleClick" Handler="ListViewItem_MouseDoubleClick"/>
</Style>
</ListView.ItemContainerStyle>
<!--以下为CTRL+C功能-->
<ListView.CommandBindings>
<CommandBinding Command="Copy" Executed="btnCopy_Click"/>
</ListView.CommandBindings>
<ListView.InputBindings>
<KeyBinding Key="C" Modifiers="Control" Command="Copy" />
</ListView.InputBindings>
<!--以上为CTRL+C功能-->
<ListView.View>
<GridView>
<GridViewColumn Header="Entry" DisplayMemberBinding="{Binding Path=UITitle}" Width="{Binding ElementName=infoCol0, Path=ActualWidth}" />
<GridViewColumn Header="Value" DisplayMemberBinding="{Binding Path=UIEntry}" Width="{Binding ElementName=infoCol1, Path=ActualWidth}" />
<GridViewColumn Header="Remark" DisplayMemberBinding="{Binding Path=UIRemark}" Width="{Binding ElementName=infoCol2, Path=ActualWidth}" />
</GridView>
</ListView.View>
</ListView>
参考上面对应位置和代码,请注意InputBindings段的Command值 与上面的CommandBinding的Command值 要对应,btnCopy_Click为处理复制的程序:
private void btnCopy_Click(object sender, RoutedEventArgs e)
{
Clipboard.SetText(Card.CardEntry.UIEntry);
}