I have this simple DataGrid in my application. Somewhere in the source I bind the ItemsSource property of it to an ObservableCollection<System.Windows.Points>. So the points are shown in the DataGrid. The problem is however I have set the TwoWay binding but when changing the point coordinate values in the DataGrid, actual point values int the ObservableCollection are not changed!
What is going wrong?
<DataGrid Name="pointList" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn Header="X" Width="200">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=X, Mode=TwoWay}"></TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Y" Width="200">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Y, Mode=TwoWay}"></TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Note I have seen this but my problem is different.
System.Windows.Pointsis a struct. You can’t bind its properties correctly.Why? Because when you do
Text="{Binding X, Mode=TwoWay}"it will bind theTextproperty of theTextBoxto theXproperty of the currentDataContext.DataContextwhich is… a structSystem.Windows.Pointsthen thePointthe databinding will modify is not the one you have assigned toDataContext.To solve your problem. Create your own
Pointtype using a class:and use
UpdateSourceTrigger=LostFocusfor your binding: