Wpf DataGridがあります。キーボードの削除キーをクリックして、ViewModelの関数を呼び出します。これにより、DataGridはViewModelのリストにバインドされます。コードは次のようになります。
データグリッド:
<DataGrid CanUserDeleteRows="False" ColumnWidth="*" ItemsSource="{Binding MyViewModel.MyList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"></DataGridTextColumn>
<DataGridTextColumn Header="Value" Binding="{Binding Value}"></DataGridTextColumn>
</DataGrid.Columns>
<DataGrid.InputBindings>
<KeyBinding Key="Delete" Command="{Binding DataContext.SomeCmd
RelativeSource={RelativeSource AncestorType=DataGrid}}" />
</DataGrid.InputBindings>
</DataGrid>
このクラスが保持するDataGridのDataContextはViewModelです
私のViewModel:
public class MyViewModel: INotifyPropertyChanged
{
private IList<xx> myList= new List<xx>();
public IList<xx> MyList
{
get
{
return myList;
}
set
{
myList= value;
NotifyPropertyChanged("MyList");
}
}
public void XM()
{
//DO SOMETHING
}
RelayCommand someCmd;
public ICommand SomeCmd
{
get
{
if (someCmd== null)
{
someCmd= new RelayCommand(param => this.XM());
NotifyPropertyChanged("SomeCmd");
}
return someCmd;
}
}
}
#region Relay Command
public class RelayCommand : ICommand
{
#region Fields
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
#endregion
#region Constructors
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
#endregion
#region ICommand Members
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
#endregion
クラスXXには、名前(文字列)と値(int)があります
コマンドへのバインドが機能せず、InitializeComponent()でエラーメッセージが表示されます。
Object reference not set to an instance of an object.
次の方法でコマンドへのリンクを記述した場合、エラーは発生しませんが、削除を押しても関数に到達しません。
<KeyBinding Key="Delete" Command="{Binding SomeCmd}" />