答案 0 :(得分:1)
每次更改AutoSuggestBox中的Text时,都可以使用绑定到ObservableCollection的AutoSuggestBox。
例如,这是您的模型:
public class App
{
public ind Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public Image Picture { get; set; }
}
您可以使用ViewModel中的参数(在本例中为搜索表达式)实现更新ObservableCollection的方法:
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
SuggestedApps = new ObservableCollection<App>();
SuggestedApps.CollectionChanged += SuggestedApps_CollectionChanged;
}
private void SuggestedApps_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
OnPropertyChanged("SuggestedApps");
}
private ObservableCollection<App> suggestedApps;
public ObservableCollection<App> SuggestedApps
{
get
{
return suggestedApps;
}
set
{
suggestedApps = value;
OnPropertyChanged("SuggestedApps");
}
}
public void SuggestForSearch(string searchExpression)
{
SuggestedApps.Clear();
//Assumgin EF as DataSource
//You can use another Search algorithm here instead of String.Contains
foreach(var item in yourDataSource.Apps.Where(x => x.Name.Contains(searchExpression.Trim())))
{
SuggestedApps.Add(item);
}
}
public void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
在您的Xaml代码中,您可以使用它将AutoSuggestBox绑定到它并定义模板:
<AutoSuggestBox x:Name="AutoSuggestBoxApps" ItemsSource="{Binding SuggestedApps}" TextChanged="AutoSuggestBoxApps_TextChanged">
<AutoSuggestBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Picture}"/>
<StackPanel>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding Category}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</AutoSuggestBox.ItemTemplate>
</AutoSuggestBox>
在TextChanged-Event的实现中,您只需从ViewModel调用SuggestForSearch方法:
private void AutoSuggestBoxApps_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
(this.DataContext as ViewModel).SuggestForSearch((sender as AutoSuggestBox).Text);
}
答案 1 :(得分:0)
有一个名为AutoSuggestBox的UWP控件,您应该阅读: https://msdn.microsoft.com/nb-no/library/windows/apps/xaml/windows.ui.xaml.controls.autosuggestbox.aspx
这应该为您提供了提供所需功能所需的工具