如何取消数据绑定更改?

时间:2018-08-07 16:53:06

标签: c# wpf data-binding

我有一个包含对象的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. :(

1 个答案:

答案 0 :(得分: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();