I am invoking the QuerySubmitted and SuggestionChosen command of the AutoSuggestBox control in WinUi 3. The commands binds to ICommand in the view model.
<AutoSuggestBox x:Name="Control2" PlaceholderText="Type a control name"
TextChanged="SearchBox_TextChanged" QueryIcon="Find" QuerySubmitted="SearchBox_QuerySubmitted"
SuggestionChosen="SearchBox_SuggestionChosen" Width="300" HorizontalAlignment="Left"/>
following code need to be converted to a DelegateCommand in view model.
public void SearchBox_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
{
if (args.ChosenSuggestion != null )
{
}
else if (!string.IsNullOrEmpty(args.QueryText))
{
}
}
Here is the question on how to do it in UWP. UWP Binding to AutoSuggestBox in MVVM
But the question and the top answer are 8 years old, is there a new(better)way to implement this in WinUi 3? Thanks.
First, please install following nuget package
https://www.nuget.org/packages/Microsoft.Xaml.Behaviors.WinUI.Managed
then you can use Interaction and bind your method (from viewmodel) in your xaml
<AutoSuggestBox x:Name="Control2" PlaceholderText="Type a control name"
TextChanged="SearchBox_TextChanged" QueryIcon="Find" Width="300" HorizontalAlignment="Left">
<i:Interaction.Behaviors>
<ic:EventTriggerBehavior EventName="QuerySubmitted">
<ic:EventTriggerBehavior.Actions>
<ic:InvokeCommandAction Command="{x:Bind ViewModel.SearchBox_QuerySubmitted}" />
</ic:EventTriggerBehavior.Actions>
</ic:EventTriggerBehavior>
<ic:EventTriggerBehavior EventName="SuggestionChosen">
<ic:EventTriggerBehavior.Actions>
<ic:InvokeCommandAction Command="{x:Bind ViewModel.SearchBox_SuggestionChosen}" />
</ic:EventTriggerBehavior.Actions>
</ic:EventTriggerBehavior>
</i:Interaction.Behaviors>
</AutoSuggestBox>
and csharp:
public void SearchBox_QuerySubmitted(AutoSuggestBoxQuerySubmittedEventArgs args)
{
}
public void SearchBox_SuggestionChosen(AutoSuggestBoxSuggestionChosenEventArgs args)
{
}