Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF databinding after Save button click

I have an app and a Settings window with TabControl containing couple of TabItems. Each of them have some fields (textboxes) which are databinded to the same Singleton object.
Is there any elegant and WPF-like way to the the databinding only after Save button click?
Right now it's databinded immediately after changing the content of the textbox, and I want that singleton have old values and update them only after clicking the save button.

like image 613
dzukica Avatar asked May 08 '26 21:05

dzukica


2 Answers

For your DataBinding object used in XAML for the Textbox, use the UpdateSourceTrigger property with value Explicit as below:

<TextBox Name="itemNameTextBox"
     Text="{Binding Path=ItemName, UpdateSourceTrigger=Explicit}" />

When you set the UpdateSourceTrigger value to Explicit, the source value only changes when the application calls the UpdateSource method as below (you can put below code in Save Click event):

BindingExpression be = itemNameTextBox.GetBindingExpression(TextBox.TextProperty);
be.UpdateSource();
like image 181
VSS Avatar answered May 10 '26 12:05

VSS


Instead of raising the notification of change on the set of each property (as that is what triggers the re-binding, and update), put all the raise notifications in the save button. Then when you click save, you save and tell the View to rebind to those (now set) properties.

To further this: Bind to non singleton properties (as you want to keep the old settings until save is clicked) - without a raise notification on those properties.

In your save button, set your singleton properties, then raise all the notifications of the other properties.

In your cancel button, set your other properties to the values of the singleton properties, and raise all the notifications.

Don't forget to set your properties to the singleton properties when the view has been loaded the first time, and raise all the notifications (just like a cancel).

like image 37
BaconSah Avatar answered May 10 '26 10:05

BaconSah