문제

I have a Wpf DataGrid, by clicking on the delete key on the keyboard I want to call a function in my ViewModel, the DataGrid bind to a list from ViewModel. The code looks like this:

The datagrid:

<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>

The DataContext of the DataGrid this class holds within it the ViewModel

My 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

On Class XX has a name (string) and value (int)

Bind to the command does not work and gives an error message on InitializeComponent():

Object reference not set to an instance of an object.

If I write the link to the command on the following way is not giving error but not coming to the function by pressing the delete:

  <KeyBinding Key="Delete" Command="{Binding SomeCmd}" />
도움이 되었습니까?

해결책

XAML should look like this:

<DataGrid CanUserDeleteRows="False" ColumnWidth="*"  ItemsSource="{Binding 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 SomeCmd}" />
    </DataGrid.InputBindings>
</DataGrid>

And don't forget to set DataContext:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new MyViewModel();
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top