Bind TextBox "textChanged" event in RelayCommand

Post date: Nov 11, 2014 4:41:25 AM

Normally we should not handle the text box textChanged event in code behind file if we committed to use MVVM pattern. 

Here I have discussed how to handle this TextBox textChanged event in MVVM patter using relay command.

Simple way of doing this is:

<TextBox Text="{Binding ViewModelProperty, UpdateSourceTrigger=PropertyChanged}"></TextBox>

The Old way of doing this is mentioned below:

Define RealyCommand in model

public RelayCommand<String> OnSearchCommand { get; set; }

          

//initialize it

 OnSearchCommand = new RelayCommand<string>(param => SearchSmartNotes(param));

//Method to call

  private void SearchSmartNotes(String strText)

        {

            SearchText = strText;

            //Do necessary things 

        }

In XAML just configure this relay command as I mentioned below

            <TextBox BorderThickness="1" BorderBrush="Black"  

                                    Grid.Row="0" Grid.Column="0" Margin="10" 

                                     VerticalContentAlignment="Stretch" x:Name="SearchBox">

                <interacitivy:Interaction.Triggers>

                    <interacitivy:EventTrigger EventName="TextChanged">

                        <interacitivy:InvokeCommandAction Command="{Binding OnSearchCommand}" CommandParameter="{Binding ElementName=SearchBox, Path=Text}">

                            

                        </interacitivy:InvokeCommandAction>

                    </interacitivy:EventTrigger>

                </interacitivy:Interaction.Triggers>

            </TextBox>

/In case if you are not aware of how to create Relay command with parameter object, then just use below code

  public class RelayCommand<T> : ICommand

    {

        private readonly Action<T> execute;

        private readonly Predicate<T> canExecute;

        public RelayCommand(Action<T> execute)

            : this(execute, null)

        {

        }

        public RelayCommand(Action<T> execute, Predicate<T> canExecute)

        {

            if (execute == null)

                throw new ArgumentNullException("execute");

            this.execute = execute;

            this.canExecute = canExecute;

        }

        [DebuggerStepThrough]

        public bool CanExecute(object parameter)

        {

            return canExecute == null || canExecute((T)parameter);

        }

        public void Execute(object parameter)

        {

            execute((T)parameter);

        }

        public void RaiseCanExecuteChanged()

        {

            if (CanExecuteChanged != null)

                CanExecuteChanged(this, new EventArgs());

        }

        public event EventHandler CanExecuteChanged;

    }