"双向绑定需要路径或XPath"当编辑WPF数据网格 [英] "Two-way binding requires Path or XPath" when edit wpf datagrid
问题描述
ContractListUserControl.XAML
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
Contract.cs
public class Contract
{
public DateTime ContractStart { get; set; }
public DateTime ContractEnd { get; set; }
public Person Person { get; set; }
}
Person.cs
Person.cs
public class Person
{
public string LastName { get; set; }
public string GivenName { get; set; }
}
ViewModel.cs
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); }
}
}
如果我设置DataGrid为只读,它的工作原理很好,问题是,当我直接编辑姓氏和给定名称DataGrid列,它会崩溃,并抛出消息InvalidOperationException异常双向绑定需要路径或XPath。但如果我只是编辑ContractStart和ContractEnd正常工作
If I set the datagrid as readonly, it works fine, problem is when I edit the LastName and GivenName DataGrid Column directly, it will crash, and throw the InvalidOperationException with message "Two-way binding requires Path or XPath". But if I just edit the ContractStart and ContractEnd it works fine.
我搜索了一些帮助,我想我遇到的这个家伙相同的情况:
的DataGrid - "双向绑定需要路径或XPath" <。 / A>
I searched for some help, and I think I meet the same situation with this guy: DataGrid - "Two-way binding requires Path or XPath."
所以问题是,这人属性为null,答案说我应该初始化结合在DataContext的,但没有说怎么对象要做到这一点。
So the problem is that the Person Property is null, and the answer said that I should initialize the object that binding in the DataContext but didn't say how to do that.
推荐答案
要实现个人财产的初始化,你可以修改如下:
to achieve the initialization of Person property you may modify 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 a constructor and initialize accordingly
这篇关于"双向绑定需要路径或XPath"当编辑WPF数据网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!