【发布时间】: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