【问题标题】:How can I cancel Data Binding changes?如何取消数据绑定更改?
【发布时间】:2018-08-07 16:53:05
【问题描述】:

我有一个包含对象的 ListView。当用户选择要编辑的项目时,会打开一个表单,他可以在其中进行更改。目前,当用户在进行更改后关闭表单时,ListView 中的原始对象会更新,即使他没有单击“保存”就关闭了表单。当用户想要取消更改时,如何防止数据绑定?


<!--xaml-->
<TextBox x:Name="tbFirstName" Text="{Binding Path=MyObject.first_name}" />
<TextBox x:Name="tbLastName" Text="{Binding Path=MyObject.last_name}"  />

public class MyObject {
     public string FirstName {get; set;}
     public string LastName {get; set;}
}

List<MyObject> listOfObjects = new List<MyObject>(); 

//user selects what he wants to edit from a ListView and clicks the Edit button
//the object is passed to a new form where he can make the desired changes.
//the editing form is automatically populated with the object thanks to data binding! this is good! :)

//Edit Button Clicked:
EditorForm ef = new EditorForm(listOfObjects[listview.SelectedIndex]);
ef.ShowDialog();

private MyObject myObject;

public EditorForm(MyObject obj) {
    InitializeComponent();
    myObject = obj;
    DataContext = this;
}        

//user makes changes to FirstName
//user decides to cancel changes by closing form.
//>>> the object is still updated thanks to data-binding. this is bad. :(

【问题讨论】:

  • XAML 中的绑定是什么样的?例如,如果它设置为TwoWay,它将自动更新任何更改。
  • 已编辑帖子以显示 xaml... 默认情况下是 TwoWay 吗?
  • 如果您不使用支持更改跟踪的数据结构,您可能必须自己实现一些东西。它可能就像在任何编辑之前存储集合的副本一样简单,如果用户取消,您可以使用它来恢复工作集。

标签: c# wpf data-binding


【解决方案1】:

更改 EditorForm 中的绑定以使用 UpdateSourceTrigger=Explicit。当您更改 UI 上的值时,这不会导致属性自动更新。相反,您必须以编程方式触发绑定以更新属性。

<!--xaml-->
<TextBox x:Name="tbFirstName" Text="{Binding Path=MyObject.first_name, UpdateSourceTrigger=Explicit}" />
<TextBox x:Name="tbLastName" Text="{Binding Path=MyObject.last_name, UpdateSourceTrigger=Explicit}"  />

当你的保存按钮被点击时,你需要从控件中获取绑定并触发更新:

var firstNameBinding = tbFirstName.GetBindingExpression(TextBox.TextProperty);
firstNameBinding.UpdateSource();
var lastNameBinding = tbLastName.GetBindingExpression(TextBox.TextProperty);
lastNameBinding.UpdateSource();

【讨论】:

  • 如果你最终有很多字段,而不仅仅是这两个,我相信你可以使用 BindingGroup 一次触发所有绑定,但你必须研究一下。我以前从未使用过 BindingGroups。
猜你喜欢
  • 2018-07-16
  • 2012-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多