Call a function when the user changes a value via an input control, but not when I am updating the value of the control state? - geocine
Expose two entry points (ex: property or function) to control the state. The input control on the view could bind to one property, and your code (ex: a command or view model) could use a different property (or function!). Both entry points would control the same data.
Assume you have a username field. When the user types the username into the input on the view, you want to perform validation. When the the view model or a command clears the username, you do not want to perform validation.
Let's see how that would look:
private string _username;
public string Username
{
get
{
return _username;
}
set
{
// Pretend this validation function exists.
ValidateUsername();
_username = value;
OnPropertyChanged(nameof(Username));
}
}
private void ClearUsername()
{
_username = null;
OnPropertyChanged(nameof(Username));
}
Based on the example above, the input control on the view would bind to the Username
property. This will ensure we perform validation on the user's input, since we call the ValidateUsername
function in the Username
setter.
Whenever we want to clear the username, we do not want to perform validation or call the ValidateUsername
function. To achieve this, we have a ClearUsername
function that will change the username value, call OnPropertyChanged so that the view updates, and not perform validation.
- We want to execute a function when the user changes a value, but not when our code changes a value
- We expose a property that the view can bind to. The setter of this property will execute the function that we wish to execute
- We expose a function (could also be a property) that our code can use. This function will bypass the property, allowing us to bypass the function in the setter that we only want the user's input to trigger