[英]TwoWay Binding ObservableCollection to DataGrid in WPF not working
我在我的應用程序中有這個簡單的DataGrid。 在源代碼的某處,我將它的ItemsSource
屬性綁定到ObservableCollection<System.Windows.Points>
。 所以這些點顯示在DataGrid
。 問題是我設置了TwoWay
綁定但是當改變DataGrid
的點坐標值時, 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
是...一個struct System.Windows.Points
然后數據綁定將修改的Point
不是你分配給DataContext
那個。
解決你的問題。 使用類創建自己的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));
}
}
並使用UpdateSourceTrigger=LostFocus
進行綁定:
<TextBox Text="{Binding Path=Y, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"></TextBox>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.