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

时间:2016-11-16 07:12:39

标签: xaml mvvm uwp template10

在UWP / Template 10应用程序中,我们需要AutoSuggestBox来更新ViewModel上的Customer属性。 AutoSuggestBox按预期过滤并从客户列表中进行选择,但ViewModel的Customer属性保持为空。

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

此演示项目名为Redstone。以下是我认为的相关代码摘录

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

最后是Customer类

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

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

1 个答案:

答案 0 :(得分:2)

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

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