"双向绑定需要Path或XPath"编辑wpf datagrid时

时间:2014-06-17 08:14:55

标签: c# wpf xaml xpath wpfdatagrid

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); }
    }
}

如果我将datagrid设置为readonly,它工作正常,问题是当我直接编辑LastName和GivenName DataGrid列时,它会崩溃,并抛出带有消息&#34的InvalidOperationException;双向绑定需要Path或XPath& #34 ;.但是如果我只是编辑ContractStart和ContractEnd就可以了。

我寻找了一些帮助,我想我和这个家伙遇到了同样的情况: DataGrid - "Two-way binding requires Path or XPath."

所以问题是Person属性为null,答案说我应该初始化DataContext中绑定的对象,但是没有说明如何做。

1 个答案:

答案 0 :(得分:8)

实现Person属性的初始化,你可以修改如下

public class Contract
{
    public Contract()
    {
        Person = new Person();
    }

    public string RankName { get; set; }
    public string RankShortName { get; set; }
    public Person Person { get; set; }
}

添加构造函数并相应地初始化