Search code examples
c#mvvmuwpevent-handlingtextchanged

How do I implement this TextChanged event handler the MVVM way?


How do I implement this event handler the MVVM way?

Other solutions I've seen have you implement a command or a property on the view model. However, this means every text changed event turns into a command execution or property set. But this event handler filters out everything except user input. How would you do that with a command or property binding?

private async void SearchBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
   if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
   {
      await this.ViewModel.RefreshAddressSuggestions(sender.Text);    
   }
}

Solution

  • How do I implement this TextChanged event handler the MVVM way?

    For your requirement, you could bind Text property with ViewModel, and check the Text value change to invoke RefreshAddressSuggestions method.

    <AutoSuggestBox Text="{x:Bind SearchText, Mode=TwoWay}"> 
    
    
    private string searchText;
    
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        if (PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    public string SearchText
    {
    
        get { return searchText; }
        set
        {
            _passWord = value;
            this.ViewModel.RefreshAddressSuggestions(value);
            OnPropertyChanged();
    
    
        }
    }