Select 在 Silverlight 应用程序中使用空格键的数据网格行

Select Datagrid row using Spacebar in Silverlight application

我在 Silverlight 应用程序中有一个 Datagrid。用户可以使用 Tab 键将焦点放在 Datagrid 上,并使用向上和向下箭头键在各行之间移动。

请指教,如何在用户为 selected 行按下空格键时触发行 select 事件。

下面是代码片段:

<Custom:ClientControl  
x:Class="TestNamespace.Modules.Views.SampleView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
mc:Ignorable="d"  
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" 
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity">
<sdk:DataGrid x:Name="dg" ...>
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="MouseLeftButtonUp">
      <i:InvokeCommandAction Command="{Binding DoSomething}" />
    </i:EventTrigger>
  </i:Interaction.Triggers>
<sdk:DataGrid.Columns>
...

试试这个:

<DataGrid>
    <DataGrid.InputBindings>
         <KeyBinding Key="Space" Command="{Binding DoSomething}"/>
    </DataGrid.InputBindings>
</DataGrid>

您可以将所选值绑定到视图模型中的 属性。

显然这个解决方案非常简单。

第 1 步:将 KeyDown 添加到 Datagrid。

<sdk:DataGrid x:Name="dg" KeyDown="dg_KeyDown">

第2步:在.XAML.CS文件中的Datagrid KeyDown事件调用处理MouseLeftButtonUp事件的方法。

private void dg_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    if (e.Key == System.Windows.Input.Key.Space)
    {
        this.viewModel.DoSomething();
    }
}