Reputation: 4427
I have a ListView that contains objects. When the user selects an item for editing, a form is opened where he can make the changes. Currently, when the user closes the form after making changes the original object in the ListView is updated, even though he closed the form without clicking Save. How can I prevent data binding when the user wants to cancel changes?
<!--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. :(
Upvotes: 0
Views: 947
Reputation: 4766
Change the binding in your EditorForm to use UpdateSourceTrigger=Explicit. This will not cause the property to automatically update when you change the value on the UI. Instead you will have to programatically trigger the binding to update the property.
<!--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}" />
When your save button is clicked, you need to get the binding from the control and trigger an update:
var firstNameBinding = tbFirstName.GetBindingExpression(TextBox.TextProperty);
firstNameBinding.UpdateSource();
var lastNameBinding = tbLastName.GetBindingExpression(TextBox.TextProperty);
lastNameBinding.UpdateSource();
Upvotes: 1