C# 将ObservableCollection双向绑定到WPF中的DataGrid不起作用
我的应用程序中有一个简单的DataGrid。在源代码中的某个地方,我将它的C# 将ObservableCollection双向绑定到WPF中的DataGrid不起作用,c#,wpf,binding,datagrid,two-way-binding,C#,Wpf,Binding,Datagrid,Two Way Binding,我的应用程序中有一个简单的DataGrid。在源代码中的某个地方,我将它的ItemsSource属性绑定到一个ObservableCollection。因此,这些点显示在数据网格中。然而,问题是我已经设置了双向绑定,但是当更改数据网格中的点坐标值时,可观测集合中的实际点值不会更改 出什么事了 <DataGrid Name="pointList" AutoGenerateColumns="False"> <DataGrid.Columns> <
ItemsSource
属性绑定到一个ObservableCollection
。因此,这些点显示在数据网格中。然而,问题是我已经设置了双向绑定,但是当更改数据网格中的点坐标值时,可观测集合中的实际点值不会更改
出什么事了
<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>
注意我看到了,但我的问题不同。System.Windows.Points
是一个结构。无法正确绑定其属性
为什么??因为当您执行Text=“{Binding X,Mode=TwoWay}”
时,它将TextBox
的Text
属性绑定到当前DataContext
的X
属性
DataContext
它是。。。一个structSystem.Windows.Points
那么数据绑定将要修改的点
不是您分配给DataContext
的点
来解决你的问题。使用类创建自己的点
类型:
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));
}
}
并使用UpdateSourceTrigger=LostFocus
进行绑定:
<TextBox Text="{Binding Path=Y, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"></TextBox>
再次说明:observablecollection与它所持有的数据无关System.Windows.Point
是一个结构。你不能用它来做这个。创建一个ViewModel。我使用这个类,但没有任何更改!无积分更新!我是否应该对我的DataGrid
进行一些更改。在单元格编辑中应该使用哪个事件?@HosseinNarimaniRad现在,ItemsSource绑定到了ObservableCollection,但它仍然不起作用?下面是代码:This.dataGrid.ItemsSource=This.points代码>点是一个可观察的集合。我试着用代码进行绑定。但是它说双向绑定需要路径或XPath。
@HosseinNarimaniRad我发现了这个问题。请看我文章的结尾。