c# – 编辑wpf datagrid时“双向绑定需要Path或XPath”

前端之家收集整理的这篇文章主要介绍了c# – 编辑wpf datagrid时“双向绑定需要Path或XPath”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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中绑定的对象,但是没有说明如何做到这一点.

解决方法

要实现Person属性的初始化,您可以修改如下
public class Contract
{
    public Contract()
    {
        Person = new Person();
    }

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

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

猜你在找的C#相关文章