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,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,() => SelectedCrew); } } }
如果我将datagrid设置为readonly,它工作正常,问题是当我直接编辑LastName和GivenName DataGrid列时,它会崩溃,并抛出InvalidOperationException,并显示消息“双向绑定需要Path或XPath”.但是,如果我只是编辑ContractStart和ContractEnd,它可以正常工作.
我寻找了一些帮助,我想我和这个家伙遇到了同样的情况:
DataGrid – “Two-way binding requires Path or XPath.”
所以问题是Person属性为null,答案说我应该初始化DataContext中绑定的对象,但是没有说明如何做到这一点.