LS Of
LS Of

Reputation: 21

WPF MVVM call methode if textbox text changed

How can I call up a method, which check if textbox is null and disabled a button, when textbox text is changed.

XAML:

<Button x:Name="button1" Content="Save" IsEnabled="{Binding BtnIsEnabled}" 

<TextBox x:Name="textBox1" Text="{Binding SelectedItem.username, ElementName=Users, UpdateSourceTrigger=PropertyChanged}" 

My Method:

    public void SaveBtnEnable()
    {
        if (!((string.IsNullOrEmpty(username)) || (string.IsNullOrEmpty(name)) || (string.IsNullOrEmpty(email))))
        {
            BtnIsEnabled = true;
        }
        else
        {
            BtnIsEnabled = false;
        }
    }



    private Boolean _BtnIsEnabled;
    public Boolean BtnIsEnabled
    {
        get
        {
            return _BtnIsEnabled;
        }
        set
        {
            _BtnIsEnabled = value;
            OnPropertyChanged("BtnIsEnabled");
        }
    }

Upvotes: 1

Views: 1391

Answers (2)

Daniele Sartori
Daniele Sartori

Reputation: 1703

In the setter of SelectedItem.username just do the check and call the metod:

public string username
{
   get {return _username;}
   set
     {
       _username = value;
       OnPropertyChanged("username");
       SaveBtnEnable();
     }
}

username is your public property and _username is the private variable in my example

Upvotes: 0

grek40
grek40

Reputation: 13438

If you use ICommand with your button and bind the Users.SelectedItem to your viewmodel (*), you can use the CanExecute method to check the viewmodel property values. Just return false if you want the button disabled.

(*) instead, you can also bind Users.SelectedItem as CommandParameter for the Execute and CanExecute functions.

Upvotes: 1

Related Questions