防止用户在RadGridView中按下Enter键时跳到下一行

时间:2020-07-27 13:24:34

标签: wpf .net-core datagrid telerik lost-focus

我有一个来自Telerik UI的RadGridView,用于WPF,具有可编辑的列。当用户编辑该列中的单元格并按 Enter 时,网格中下一行的同一单元格将获得焦点。

我希望用户刚刚编辑的单元格失去焦点。该如何制作MVVM风格?

1 个答案:

答案 0 :(得分:0)

您可以通过编写自定义键盘命令提供程序来更改此行为。此提供程序将覆盖默认的Enter按下操作。通过将SelectedItem设置为null,提交编辑并取消选择单元格。

public class CustomKeyboardCommandProvider : DefaultKeyboardCommandProvider
{
   private readonly GridViewDataControl _grid;

   public CustomKeyboardCommandProvider(GridViewDataControl grid)
      : base(grid)
   {
      _grid = grid;
   }

   public override IEnumerable<ICommand> ProvideCommandsForKey(Key key)
   {
      var commands = base.ProvideCommandsForKey(key).ToList();

      if (key != Key.Enter)
         return commands;

      commands.Clear();
      commands.Add(RadGridViewCommands.CommitEdit);

      _grid.SelectedItem = null;

      return commands;
   }
}

您必须分配新的提供者。最简单的方法是在代码隐藏中,因为它具有构造函数参数。

MyRadDataGridView.KeyboardCommandProvider = new CustomKeyboardCommandProvider(TestGridView);

或者,创建一个TriggerAction<RadGridView>并将其附加到网格视图的Loaded事件。

public class SetCustomKeyboardCommandProviderAction : TriggerAction<RadGridView>
{
   protected override void Invoke(object parameter)
   {
      AssociatedObject.KeyboardCommandProvider = new CustomKeyboardCommandProvider(AssociatedObject);
   }
}
<telerik:RadGridView>
   <b:Interaction.Triggers>
      <b:EventTrigger EventName="Loaded">
         <local:SetCustomKeyboardCommandProviderAction/>
      </b:EventTrigger>
   </b:Interaction.Triggers>
   <!-- ...other definitions. -->
</telerik:RadGridView>