使用模板 10 在 UWP 中将 AutoSuggestBox 绑定到 ViewModel 属性

Bind AutoSuggestBox to ViewModel Property in UWP using Template 10

在 UWP/Template 10 应用程序中,我们需要一个 AutoSuggestBox 来更新 ViewModel 上的客户 属性。 AutoSuggestBox 按预期从客户列表中筛选和选择,但 ViewModel 的 Customer 属性 仍然为空。

AutoSuggestBox 从数据库中填充。我省略了该代码,因为它运行良好。

这个演示项目叫做红石。以下是我认为是相关代码摘录

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}">

以及来自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;
    }

最后是客户class

public class Customer
{
    public Guid CustomerId { get; set; } = Guid.NewGuid();
    public string FileAs { get; set; }
}

AutoSuggestBox 正在按预期过滤和显示。为什么 MainPageViewModel 的 Customer 属性 保持为空?

根据@tao 的建议,我修改了 ViewModel,如下所示,现在一切都是 tickety-boo

        public void FindCustomer_SuggestionChosen(AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args)
    {
        CustomerLookup selectedCustomer = args.SelectedItem as CustomerLookup;
        this.Customer = CustomersService.GetCustomer(selectedCustomer.CustomerId);
    }