In a UWP/Template 10 app we require an AutoSuggestBox to update the Customer property on a ViewModel. The AutoSuggestBox filters and selects from the customer list as expected, but the Customer property of the ViewModel remains null.
The AutoSuggestBox populates from a database. I've omitted that code as it is working well.
This demo project is called Redstone. Below are what I believe to be the relevant code excerpts
MainPage.xaml
<Page x:Class="Redstone.Views.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Behaviors="using:Template10.Behaviors"
xmlns:Core="using:Microsoft.Xaml.Interactions.Core"
xmlns:Interactivity="using:Microsoft.Xaml.Interactivity"
xmlns:controls="using:Template10.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:uc="using:Redstone.UserControls"
xmlns:local="using:Redstone.Views"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:converters="using:Redstone.Validation"
xmlns:behaviors="using:Template10.Behaviors"
xmlns:vm="using:Redstone.ViewModels"
mc:Ignorable="d">
<Page.DataContext>
<vm:MainPageViewModel x:Name="ViewModel" />
</Page.DataContext>
<AutoSuggestBox Name="CustomerAutoSuggestBox"
Width="244"
Margin="0,5"
TextMemberPath="{x:Bind ViewModel.Customer.FileAs, Mode=TwoWay}"
PlaceholderText="Customer"
QueryIcon="Find"
TextChanged="{x:Bind ViewModel.FindCustomer_TextChanged}"
SuggestionChosen="{x:Bind ViewModel.FindCustomer_SuggestionChosen}">
and the relevant excerpts from MainPageViewModel
public class MainPageViewModel : ViewModelBase
{
Customer _Customer = default(Customer);
public Customer Customer { get { return _Customer; } set { Set(ref _Customer, value); } }
public void FindCustomer_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
{
sender.ItemsSource = CustomerLookupList.Where(cl => cl.Lookup.IndexOf(sender.Text, StringComparison.CurrentCultureIgnoreCase) > -1).OrderBy(cl => cl.FileAs);
}
}
public void FindCustomer_SuggestionChosen(AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args)
{
CustomerLookup selectedCustomer = args.SelectedItem as CustomerLookup;
sender.Text = selectedCustomer.FileAs;
}
Finally the Customer class
public class Customer
{
public Guid CustomerId { get; set; } = Guid.NewGuid();
public string FileAs { get; set; }
}
The AutoSuggestBox is filtering and displaying as expected. Why does the Customer property of MainPageViewModel remain null?
Following advice from @tao I have modified the ViewModel as below and all is now tickety-boo
public void FindCustomer_SuggestionChosen(AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args)
{
CustomerLookup selectedCustomer = args.SelectedItem as CustomerLookup;
this.Customer = CustomersService.GetCustomer(selectedCustomer.CustomerId);
}