Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Two-way binding requires Path or XPath" when edit 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, 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.

I searched for some help, and I think I meet 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 binding in the DataContext but didn't say how to do that.

like image 895
Elliot Li Avatar asked Jun 17 '14 08:06

Elliot Li


1 Answers

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

like image 55
pushpraj Avatar answered Sep 22 '22 06:09

pushpraj