TwoWay Binding ObservableCollection for DataGrid in WPF not working
I have this simple DataGrid in my application. Somewhere in the source I bind a property ItemsSource
to ObservableCollection<System.Windows.Points>
. Thus, the points are shown in DataGrid
. However, the problem is related to snapping TwoWay
, but when the point coordinate values change to DataGrid
the actual point's int values ObservableCollection
do not change!
What's 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've seen this one , but my problem is different.
source to share
System.Windows.Points
- struct . You cannot bind its properties correctly.
Why? Because when you execute Text="{Binding X, Mode=TwoWay}"
, it will bind the property of the Text
property TextBox
to the property of the X
current one DataContext
.
DataContext
, which is ... a struct System.Windows.Points
, then the Point
data binding changes not the one you assigned DataContext
.
To solve your problem. Create your own type Point
using the class :
public class Point : INotifyPropertyChanged
{
private double x;
public double X
{
get { return x; }
set
{
if (x != value)
{
x = value;
OnPropertyChanged("X");
}
}
}
private double y;
public double Y
{
get { return y; }
set
{
if (y != value)
{
y = value;
OnPropertyChanged("Y");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
and use UpdateSourceTrigger=LostFocus
for your binding:
<TextBox Text="{Binding Path=Y, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"></TextBox>
source to share