0
votes

Here's my problem, when application starts up then user selects textbox. Without typing anything user clicks tab to select next textbox. This should trigger the setter method in viewmodel for the first textbox binding. But it seems not to happen.

In viewmodel:

private string _username;
public string Username
{
    get { return _username; }
    set
    {
        _username = value;
        RaisePropertyChanged("Username");
        Validator.Validate(() => Username);
    }
} 

And in xaml:

<TextBox Text="{Binding Username, Mode=TwoWay, ValidatesOnDataErrors=True}" />

Username setter method gets called when i start to type something, then erase it and move focus to something else. Datacontext is properly set and working.

1) User sets focus to Username textbox, does not type anything

2) User moves focus to next item on form

Result = Setter method in view model is not called when Username textbox loses focus

Result i need = Setter method is called even when user does not type anything

1
"This should trigger the setter method" -- please explain precisely why you believe this to be true. If the contents of the TextBox haven't changed, why would the view model's setter be called? Why not just handle the LostFocus event if you want to know when the control has lost focus? And why would you want to do a property-changed notification and data validation when the value hasn't actually changed? I find this question very confusing.Peter Duniho
When user does not enter anything to textbox and just moves to next control then i need to be able to show validation error. But if the setter is not called then i cant validate if the field is empty or not.hs2d
Look at UpdateSourceTrigger property of Binding classMaxwe11
@Maxwe11, default for textbox is LostFocus and thats what i want. So i dont need to set it again.hs2d
@PeterDuniho, yes i could just handle the LostFocus event in the code behind. But when there is many textboxes on the form then i would have to do that for all of them...hs2d

1 Answers

0
votes

If the intention is to trigger the validation status immediately (which is what I get from your "need to call the setter anyway"), then why not just use a Loaded event at the Window level and assign String.Empty so that the validation code is triggered regardless?

Or even better, use IDataErrorInfo which performs validation during the getter call thus meaning the first time the TextBox loads, the IDataErrorInfo interface will be called and the property validated.