我有一个包含对象的ListView。当用户选择要编辑的项时,会打开一个表单,他可以在其中进行更改。当前,当用户在更改后关闭表单时,ListView中的原始对象将被更新,即使他没有单击Save就关闭了该表单。当用户想要取消更改时,如何防止数据绑定?
<!--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. :(
发布于 2018-08-07 18:36:33
将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();
https://stackoverflow.com/questions/51731838
复制相似问题