ContractListUserControl.XAML
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Path=ContractList}" SelectedItem="{Binding Path=SelectedContract}"> <DataGrid.Columns> <DataGridTextColumn Binding="{Binding Path=Person.LastName}" Header="Last Name" /> <DataGridTextColumn Binding="{Binding Path=Person.GivenName}" Header="Given Name" /> <DataGridTextColumn Binding="{Binding Path=ContractStart, StringFormat=dd/MM/yyyy, Mode=TwoWay}" Header="Contract Start" /> <DataGridTextColumn Binding="{Binding Path=ContractEnd, StringFormat=dd/MM/yyyy, Mode=TwoWay}" Header="Contract End" /> </DataGrid.Columns> </DataGrid>
Contract.cs
public class Contract { public DateTime ContractStart { get; set; } public DateTime ContractEnd { get; set; } public Person Person { get; set; } }
Person.cs
public class Person { public string LastName { get; set; } public string GivenName { get; set; } }
ViewModel.cs
public class ContractListViewModel : INotifyPropertyChanged { private ObservableCollection<Contract> _contractList; public ObservableCollection<Contract> ContractList { get { return _contractList; } set { SetField(ref _contractList, value, () => ContractList); }
If I set the datagrid as readonly, it works fine, the problem is that I directly edit the LastName and DataName DataGrid columns, it crashes and throws an InvalidOperationException with the message "Two-way binding requires Path or XPath." But if I just edit ContractStart and ContractEnd, it works fine.
I was looking for some help and I think I am facing the same situation with this guy: DataGrid - "Two-way binding requires Path or XPath."
So the problem is that the Person property is null, and the answer said that I should initialize the object that binds in the DataContext, but did not say how to do it.
source share