"Bilateral binding requires Path or XPath" when editing a wpf datagrid

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); } // Same as OnPropertyChanged } private Contract _selectedContract; public Contract SelectedContract { get { return _selectedCrew; } set { SetField(ref _selectedCrew, value, () => SelectedCrew); } } } 

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.

+6
source share
1 answer

to achieve the initialization of the Person property, you can change as follows

 public class Contract { public Contract() { Person = new Person(); } public string RankName { get; set; } public string RankShortName { get; set; } public Person Person { get; set; } } 

add constructor and initialize accordingly

+8
source

Source: https://habr.com/ru/post/970928/


All Articles