Search code examples
c#wpfmvvmdata-bindingdatagrid

MVVM SelectedItem of DataGrid shows as null when setting it as CommandParameter and recieving it


Problem

I am trying to set the CommandParameter as GridName.SelectedItem to the command, but in my paramater command, it shows as null value.

Error code - when executing the button

An unhandled exception of type 'System.NullReferenceException' occurred in TestingOnly.exe
Additional information: Object reference not set to an instance of an object.

Full Code

View

<DataGrid x:Name="FSQMGrid" 
          ItemsSource="{Binding TestList}"
          AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding ID}" Header="Id"/>
        <DataGridTextColumn Binding="{Binding Name}" Header="Name"/>
    </DataGrid.Columns>
</DataGrid>

<StackPanel Grid.Column="1">
    <Button Content="Update" 
            Command="{Binding FSQMUpdateRecordCommand}" 
            CommandParameter="{Binding FSQMGrid.SelectedItem}"/>
</StackPanel>

Model

public class BasicTestModel
{
    public int ID { get; set; }
    public string Name { get; set; }
}

View Model

public class FSQM_RecordViewModel : BaseViewModel
{

    private List<BasicTestModel> _TestList { get; set; }

    public List<BasicTestModel> TestList { get { return _TestList; } set { _TestList = value; OnPropertyChanged("TestList"); } }

    public ICommand FSQMUpdateRecordCommand { get; set; }

    public FSQM_RecordViewModel()
    {
        TestList = new List<BasicTestModel>
        {
            new BasicTestModel { ID = 1, Name = "Name 1"},
            new BasicTestModel { ID = 2, Name = "Name 2"},
            new BasicTestModel { ID = 3, Name = "Name 3"}
        };

        FSQMUpdateRecordCommand = new FSQMUpdateRecordCommand(this);
    }
}

Command

public class FSQMUpdateRecordCommand : ICommand
{
    public FSQM_RecordViewModel viewModel { get; set; }

    public FSQMUpdateRecordCommand(FSQM_RecordViewModel viewModel)
    {
        this.viewModel = viewModel;
    }

    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        System.Windows.MessageBox.Show(parameter.ToString()); // Shows as null
    }
}

What I have tried

I have found other similar questions on here that mentioned to set the Mode=TwoWay within the view, but that didn't change anything for me.

Question

Where I'm I going wrong? How do I fix this null value error?

Goal

I am simply aiming to get the selected ID and Name from the datagrid and use it in the Command class.


Solution

  • Binding with path FSQMGrid.SelectedItem cannot be resolved. There is no FSQMGrid property in DataContext. FSQMGrid is a name of UI element

    it should be:

    CommandParameter="{Binding Path=SelectedItem, ElementName=FSQMGrid}"