具有显式源更新的 WPF 双向绑定不起作用
本文关键字:WPF 绑定 不起作用 更新 | 更新日期: 2023-09-27 18:33:23
我绑定了可观察集合 - 数据网格(模式 - 双向),但我想自己使用 UpdateSource() 调用更新集合并禁用自动源更新。我设置绑定像
ItemsSource="{Binding Path=Bezier.BezierPoints, Mode=TwoWay, UpdateSourceTrigger=Explicit}"
但我的收藏仍然自动更新。我的代码示例如下。我做错了什么?我的 XAML:
<DataGrid Name="BezierPointsDataGrid" Margin="5" AutoGenerateColumns="False"
Grid.Column="0" Grid.Row="0" Background="White"
ItemsSource="{Binding Path=Bezier.BezierPoints, Mode=TwoWay, UpdateSourceTrigger=Explicit}">
<DataGrid.Columns>
<DataGridTextColumn Header="X" Binding="{Binding Path=X}" Width="1*"/>
<DataGridTextColumn Header="Y" Binding="{Binding Path=Y}" Width="1*"/>
</DataGrid.Columns>
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding Path=UpdateBezierPointsCommand}" CommandParameter="{Binding ElementName=BezierPointsDataGrid}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</DataGrid>
我的视图模型:
class BezierCurveViewModel : INotifyPropertyChanged
{
#region Bezier curve model
private BezierCurveModel _bezier;
public BezierCurveModel Bezier
{
get { return _bezier; }
set
{
if (_bezier == value)
return;
_bezier = value;
OnPropertyChanged("Bezier");
}
}
#endregion
#region Commands
public ICommand UpdateBezierPointsCommand { set; get; }
#endregion
#region Constructor
public BezierCurveViewModel()
{
UpdateBezierPointsCommand = new Command(a => ((DataGrid)a).GetBindingExpression(DataGrid.ItemsSourceProperty).UpdateSource());
Bezier = new BezierCurveModel();
}
#endregion
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
我的模型:
public ObservableCollection<DPoint> BezierPoints { private set; get; }
编辑:我将ObservableCollection更改为DataTable以实现预期的行为。但我仍然对解决这个问题感兴趣,因为我想了解为什么任何与可观察集合的绑定都会在编辑表后更新源(阅读我对 Andrew 帖子的评论)。
在这里,您已经设置了视图以显式更新 BezierPoints 属性,因为这就是您绑定 ItemsSource 的内容。
我假设您真正想要的是对各个点的属性使用显式更新触发器。 为此,您需要将 DataGridTextColum 绑定更改为 UpdateSourceTrigger=Explicit。
作为旁注,您似乎根本不可能从视图更新贝塞尔积分集合,因为该物业有一个私人二传手。