【发布时间】:2021-04-23 15:03:00
【问题描述】:
问题
我正在尝试将 CommandParameter 设置为命令的 GridName.SelectedItem,但在我的参数命令中,它显示为空值。
错误代码 - 执行按钮时
An unhandled exception of type 'System.NullReferenceException' occurred in TestingOnly.exe
Additional information: Object reference not set to an instance of an object.
完整代码
查看
<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>
型号
public class BasicTestModel
{
public int ID { get; set; }
public string Name { get; set; }
}
查看模型
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);
}
}
命令
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
}
}
我的尝试
我在这里发现了其他类似的问题,提到在视图中设置Mode=TwoWay,但这对我来说并没有改变任何东西。
问题
我哪里错了?如何解决这个空值错误?
目标
我的目标只是从数据网格中获取选定的ID 和Name 并在Command 类中使用它。
【问题讨论】:
标签: c# wpf mvvm data-binding datagrid