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;
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; } }
source share