Associating UWP with AutoSuggestBox in MVVM

I invoke the QuerySubmitted command of the AutoSuggestBox control in UWP. The command is attached to ICommand in the view model. the problem is that this requires accepting AutoSuggestBoxQuerySubmittedEventArgs, which is a clean user interface, and this is not acceptable in MVVM.

my code is as follows:

<AutoSuggestBox Name="SearchAutoSuggestBox" PlaceholderText="Search by keywords" QueryIcon="Find" > <interactivity:Interaction.Behaviors> <core:EventTriggerBehavior EventName="QuerySubmitted"> <core:InvokeCommandAction Command="{x:Bind ViewModel.SearchCommand}" /> </core:EventTriggerBehavior> </interactivity:Interaction.Behaviors> </AutoSuggestBox> 

and my model looks like this:

 public DelegateCommand<AutoSuggestBoxQuerySubmittedEventArgs> SearchCommand { get; } public MainPageViewModel() { SearchCommand = new DelegateCommand<AutoSuggestBoxQuerySubmittedEventArgs>(ExecuteMethod); } private void ExecuteMethod(AutoSuggestBoxQuerySubmittedEventArgs o) { // CODE HERE } 

ofcours AutoSuggestBoxQuerySubmittedEventArgs is not acceptable in the view model. looking for alternatives ... the same goes for SuggestionChosen ...

+5
source share
4 answers

InvokeCommandAction has a parameter called InputConverter that you can use to convert the event arguments to some other parameter that you can pass to the ViewModel.

First create an IValueConverter class to extract arguments like this from your events: -

 public class AutoSuggestQueryParameterConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { // cast value to whatever EventArgs class you are expecting here var args = (AutoSuggestBoxQuerySubmittedEventArgs)value; // return what you need from the args return (string)args.ChosenSuggestion; } } 

Then use this converter in your XAML as follows:

 <Page.Resources> <converters:AutoSuggestQueryParameterConverter x:Key="ArgsConverter" /> </Page.Resources> <AutoSuggestBox Name="SearchAutoSuggestBox" PlaceholderText="Search by keywords" QueryIcon="Find"> <interactivity:Interaction.Behaviors> <core:EventTriggerBehavior EventName="QuerySubmitted"> <core:InvokeCommandAction Command="{x:Bind ViewModel.SearchCommand}" InputConverter="{StaticResource ArgsConverter}" /> </core:EventTriggerBehavior> </interactivity:Interaction.Behaviors> </AutoSuggestBox> 

Finally, in your view model, modify your command to accept the string as a parameter. So, you will have the following in your vm:

 public DelegateCommand<string> SearchCommand { get; } public MainPageViewModel() { SearchCommand = new DelegateCommand<string>(ExecuteMethod); } private void ExecuteMethod(string o) { // CODE HERE } 
+8
source

You can bind the search string (the "Text" property) to the property of the view model and to methods without parameters. Thus, the view model will not deal with user interface objects:

XAML:

 <AutoSuggestBox Header="What your name?" TextChanged="{x:Bind ViewModel.FilterUsuals}" QuerySubmitted="{x:Bind ViewModel.ProcessQuery}" SuggestionChosen="{x:Bind ViewModel.ProcessChoice}" ItemsSource="{x:Bind ViewModel.Usuals, Mode=OneWay}" Text="{x:Bind ViewModel.SearchText, Mode=TwoWay}" QueryIcon="Find" /> 

Code behind:

 public class MainPageViewModel : SomeViewModelBaseClass { /* Boilerplate code and constructor not included */ private string _SearchText; public string SearchText {/* getter and setter INotyfyPropertyChange compliant */ } private List<string> _Usuals; // Initialized on constructor public string Usuals {/* getter and setter INotyfyPropertyChange compliant */ } public void FilterUsuals() { // the search string is in SearchText Example: Usuals = _UsualsStore.Where(u => u.Contains(_SearchText.ToLower())).ToList(); } public void ProcessQuery() { /* TODO - search string is in SearchText */ } public void ProcessChoice() { /* TODO - search string is in SearchText */ } } 
+3
source

If you do not miss the non pure MVVM method.

MainPage.xaml :

 <AutoSuggestBox Name="SearchAutoSuggestBox" PlaceholderText="Search by keywords" QueryIcon="Find" QuerySubmitted="{x:Bind ViewModel.SearchQuerySubmitted}" IsEnabled="{x:Bind ViewModel.CanExecuteSearchCommand, Mode=TwoWay}" > </AutoSuggestBox> 

MainPageViewModel.cs :

 public class MainPageViewModel : INotifyPropertyChanged { private bool _canExecuteSearchCommand; public MainPageViewModel() { this.CanExecuteSearchCommand = true; } public bool CanExecuteSearchCommand { get { return _canExecuteSearchCommand; } set { bool changed = _canExecuteSearchCommand != value; _canExecuteSearchCommand = value; if(changed) this.OnPropertyChanged(); } } public void SearchQuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args) { // Just example disabling SearchBox this.CanExecuteSearchCommand = false; } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } 

MainPage.cs :

 MainPageViewModel ViewModel = new MainPageViewModel(); 
+1
source

binding UWP Command/Delegate to AutoSuggestBox in MVVM

For UWP Mobile Application

Make class DelegateCommand

 public class DelegateCommand<T> : ICommand { private readonly Action<T> executeAction; Func<object, bool> canExecute; public event EventHandler CanExecuteChanged; public DelegateCommand(Action<T> executeAction) : this(executeAction, null) { //var a = ((Page)(((Func<object, bool>)(executeAction.Target)).Target)).Name; //((ViewModel.VMBranchSelection)(executeAction.Target)).; } public DelegateCommand(Action<T> executeAction, Func<object, bool> canExecute) { this.executeAction = executeAction; this.canExecute = canExecute; } public bool CanExecute(object parameter) { return canExecute == null ? true : canExecute(parameter); } public void Execute(object parameter) { executeAction((T)parameter); } public void RaiseCanExecuteChanged() { EventHandler handler = this.CanExecuteChanged; if (handler != null) { handler(this, new EventArgs()); } } } 

In view model

  public ICommand SuggessionSelectCity_QuerySubmitted { get { return new DelegateCommand<AutoSuggestBoxQuerySubmittedEventArgs>(this.SuggessionSelectCityQuerySubmitted); } } private void SuggessionSelectCityQuerySubmitted(AutoSuggestBoxQuerySubmittedEventArgs obj) { if (obj.ChosenSuggestion != null) { AutosuggestionTextBoxName.Text = ((ModelName) (obj.ChosenSuggestion)).Model Property name; //or AutosuggestionTextBoxName.Text =(obj.ChosenSuggestion).property name } else { } } 

In XAML code

 <AutoSuggestBox Grid.Column="1" x:Name="SuggessionSelectCity" PlaceholderText="Search by keywords" QueryIcon="Find" ItemsSource="{Binding PApplicantCityList}" HorizontalAlignment="Center" VerticalAlignment="Center" DisplayMemberPath="Description" Width="250" Height="45"> <Interactivity:Interaction.Behaviors> <Core:EventTriggerBehavior EventName="TextChanged"> <Core:EventTriggerBehavior.Actions> <Core:InvokeCommandAction Command="{Binding SuggessionSelectCityTextChange}"/> </Core:EventTriggerBehavior.Actions> </Core:EventTriggerBehavior> <Core:EventTriggerBehavior EventName="QuerySubmitted"> <Core:EventTriggerBehavior.Actions> <Core:InvokeCommandAction Command="{Binding SuggessionSelectCity_QuerySubmitted}"/> </Core:EventTriggerBehavior.Actions> </Core:EventTriggerBehavior> <Core:EventTriggerBehavior EventName="SuggestionChosen"> <Core:EventTriggerBehavior.Actions> <Core:InvokeCommandAction Command="{Binding SuggessionSelectCitySuggestionChosen}"/> </Core:EventTriggerBehavior.Actions> </Core:EventTriggerBehavior> </Interactivity:Interaction.Behaviors> </AutoSuggestBox> </Grid> 

Create a list in View Model for Autosuggestion TextBox Itemssource

 private ObservableCollection<ResultMasterModel> ApplicantCityList; public ObservableCollection<ResultMasterModel> PApplicantCityList { get { return ApplicantCityList; } set { this.SetProperty(ref this.ApplicantCityList, value); } } 

add some hard code value to the list above

Create model in model folder

 public class ResultMasterModel { public string Code { get; set; } public string Description { get; set; } } 
0
source

Source: https://habr.com/ru/post/1239926/


All Articles