Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Databinding textbox

Well I'm a bit of a newbie with MVVM so please any tips ans suggestions are welcome :)

I want to keep track of a username and password and the user can set this on a Settings view. In the SettingsViewModel I have 2 properties for these 2 fields that are bound to the text boxes on the view. I added a Save button on the app bar and through a RelayCommand it executes a method on the ViewModel when the user clicks it.

Now what goes wrong:

  • When the user is typing in a textbox and doesn't exit it, but presses the save directly, the value is not databinded yet. So how do you solve this? Is the only way using the coding4fun:TextBoxBinding.UpdateSourceOnChange="True" feature from the coding4fun library?

  • When a user enters data in a textbox and it is databound, leaving the settings page and returning to it will still keep this data. How do I clear this as long as the user hasn't pressed the save button? Kinda weird that you keep data on the page when it hasn't been saved yet... But because I use MVVMLight the page is statically created in the ViewModelLocator and stays 'active' as long as the program is running.

Well like I said, any hints, tips, suggestions are welcome :)

like image 967
Depechie Avatar asked Jun 17 '26 09:06

Depechie


1 Answers

Re 1: This is a known issue where if the last control that had focus was a textbox, and you click on an app-bar button, its latest value is not databound properly. In my appbar click event handlers, I invoke the following method to force a databind if the last control to have focus was a textbox or passwordbox.

private static void UpdateBoundText()
{
    var focusObj = FocusManager.GetFocusedElement();
    if (focusObj == null) return;
    var binding = focusObj is TextBox ? ((TextBox)focusObj).GetBindingExpression(TextBox.TextProperty)
                : focusObj is PasswordBox ? ((PasswordBox)focusObj).GetBindingExpression(PasswordBox.PasswordProperty) 
                : null;
    if (binding != null)
    {
        binding.UpdateSource();
    }
}
like image 129
Damian Avatar answered Jun 21 '26 01:06

Damian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!