4

私はwpf固有の問題を抱えています。データグリッドの選択された行を Command パラメータとしてコマンドに渡すキーバインディングを定義することにより、データグリッドから行を削除しようとしています。

これは私のキーバインドです:

<UserControl.Resources >
    <Commands:CommandReference x:Key="deleteKey" Command="{Binding DeleteSelectedCommand}"/>
</UserControl.Resources>

<UserControl.InputBindings>
    <KeyBinding Key="D" Modifiers="Control" Command="{StaticResource deleteKey}"/>
</UserControl.InputBindings>

DeleteSelectedCommand までデバッグできるため、これが基本的に機能することはわかっています。ただし、DeleteSelectedCommand は Datagrid の行が Call Parameter として削除されることを期待しているため、例外が発生します。

キーバインディングを介して SelectedRow を渡すにはどうすればよいですか?

可能であれば、コード ビハインドを変更せずに、これを XAML でのみ実行したいと考えています。

4

3 に答える 3

12

DataGrid に名前がある場合は、その方法でターゲットを絞ることができます。

<KeyBinding Key="D" Modifiers="Control" Command="{StaticResource deleteKey}"
            CommandParameter="{Binding SelectedItem, ElementName=myDataGrid}"/>

(注:CommandParameter依存関係プロパティに変更されたため、.NET 4 (およびおそらく次のバージョン) でのみバインド可能です)

于 2011-11-21T14:17:56.393 に答える
2

コマンド パラメーターを使用するのではなく、選択した行を格納するプロパティを作成します。

private Model row;

 public Model Row
     {
         get { return row; }
         set
         {
             if (row != value)
             {
                 row = value;
                 base.RaisePropertyChanged("Row");
             }
         }
     }

Model は、グリッドが表示しているオブジェクトのクラスです。プロパティを使用するには、データグリッドに selectedItem プロパティを追加します。

<DataGrid SelectedItem="{Binding Row, UpdateSourceTrigger=PropertyChanged}"/> 

次に、コマンドが行を介してメソッドに渡されるようにします。

    public ICommand DeleteSelectedCommand
     {
         get
         {
             return new RelayCommand<string>((s) => DeleteRow(Row));
         }
     }

そしてあなたのキーバインディングのために:

 <DataGrid.InputBindings>
            <KeyBinding Key="Delete" Command="{Binding DeleteSelectedCommand}" />
        </DataGrid.InputBindings>

それが役立つことを願っています!

于 2011-11-22T09:40:47.693 に答える
0

KeyBinding には CommandParameter というプロパティがあり、ここで設定されたものはすべて渡されます。ただし、コマンドで見つかったように、依存関係プロパティではありません (3.5 では、4.0 については HB の回答を参照してください)。

コマンドのバインドに使用したのと同じソリューションを使用する必要があります。ここに例があります http://www.wpfmentor.com/2009/01/how-to-add-binding-to-commandparameter.html

 <DataGrid x:Name="grid">
  <DataGrid.Resources>
    <WpfSandBox:DataResource x:Key="cp" BindingTarget="{Binding SelectedItem, ElementName=grid}" />
  </DataGrid.Resources>
  <DataGrid.InputBindings>
    <KeyBinding Key="q" Modifiers="Control" Command="{x:Static WpfSandBox:Commands.Delete}">
      <KeyBinding.CommandParameter>
        <WpfSandBox:DataResourceBinding DataResource="{StaticResource cp}"/>
      </KeyBinding.CommandParameter>
    </KeyBinding>
  </DataGrid.InputBindings>
  <DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Value}"  />
    <DataGridTextColumn Binding="{Binding Value}"  />
  </DataGrid.Columns>
</DataGrid>
于 2011-11-21T14:30:28.167 に答える