Search code examples
eventsmvvmtextbox

Handle TextBox event such as Text_changed in ViewModel


For handling Button Click in View-model we hook Button-Command with a ViewModel Property.

<Button Command="ButtonCommand"/>


class MyViewModel
{
   ICommand _buttonCommand;
   public MyViewModel()
   {
     _buttonCommand=new CommandHandler(() => Buttonfunction(), "true");
   }

   public ICommand ButtonCommand
   {
    get{ return _buttonCommand;}    
   }

   private void Buttonfunction
   { //do something. }
}

public class CommandHandler : ICommand
{
 private Action _action;
 private bool _canExecute;
 public CommandHandler(Action action, bool canExecute)
 {
    _action = action;
    _canExecute = canExecute;
 }

 public bool CanExecute(object parameter)
 {
    return _canExecute;
 }

 public event EventHandler CanExecuteChanged;

 public void Execute(object parameter)
 {
    _action();
 }
}

Similarly What can be done for TextBox events. How can we Bind a Command with TextBox Event in .NET 3.5.

<TextBox TextChanged=?/>

Solution

  • You must bind it to a property first, Then use the setter of that property as your text change event. In your xaml:

    <TextBox Text="{Binding Name}" />
    

    In your Viewmodel

    private string _name;
    
    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
            yourTextChangeEvent();
        }
    }