[英]TwoWay Binding ObservableCollection to DataGrid in WPF not working
I have this simple DataGrid in my application. 我在我的应用程序中有这个简单的DataGrid。 Somewhere in the source I bind the
ItemsSource
property of it to an ObservableCollection<System.Windows.Points>
. 在源代码的某处,我将它的
ItemsSource
属性绑定到ObservableCollection<System.Windows.Points>
。 So the points are shown in the DataGrid
. 所以这些点显示在
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! 问题是我设置了
TwoWay
绑定但是当改变DataGrid
的点坐标值时, ObservableCollection
中的实际点值不会改变!
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.Points
is a struct . System.Windows.Points
是一个结构 。 You can't bind its properties correctly. 您无法正确绑定其属性。
Why? 为什么? Because when you do
Text="{Binding X, Mode=TwoWay}"
it will bind the Text
property of the TextBox
to the X
property of the current DataContext
. 因为当你执行
Text="{Binding X, Mode=TwoWay}"
它会将TextBox
的Text
属性绑定到当前DataContext
的X
属性。
DataContext
which is... a struct System.Windows.Points
then the Point
the databinding will modify is not the one you have assigned to DataContext
. DataContext
是...一个struct System.Windows.Points
然后数据绑定将修改的Point
不是你分配给DataContext
那个。
To solve your problem. 解决你的问题。 Create your own
Point
type using a class : 使用类创建自己的
Point
类型:
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: 并使用
UpdateSourceTrigger=LostFocus
进行绑定:
<TextBox Text="{Binding Path=Y, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"></TextBox>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.