我在填充和显示XLabs.Forms.Control:AutoCompleteView的建议列表时遇到了困难。我已经将ViewModel中的可观察集合绑定到autocompleteview xaml的Suggestions属性。
根据我的调试代码(即只是将查询返回的内容写入调试输出的循环),我的查询返回项目,所以我认为问题在于只显示所述项目。
这里是Xaml和ViewModel的代码(Store类有StoreName属性/字段)
XAML
<ContentPage.Resources>
<ResourceDictionary>
<DataTemplate x:Key="SugestionItemTemplate">
<ViewCell Height="60">
<ViewCell.View>
<StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<Label Text="{Binding StoreName}" VerticalOptions="Center" HorizontalOptions="Start" />
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ResourceDictionary>
</ContentPage.Resources>
<StackLayout HorizontalOptions="Center" Spacing="10">
<StackLayout.BindingContext>
<vm:CreateSaleViewModel />
</StackLayout.BindingContext>
<Label Text="Store" />
<controls:AutoCompleteView Placeholder="Type a store"
SuggestionItemDataTemplate="{StaticResource SugestionItemTemplate}"
Text="{Binding StoreQuery}"
ShowSearchButton="True"
SearchBackgroundColor = "White"
SearchCommand ="{Binding SearchCmd}"
Suggestions="{Binding StoreSuggestions}" />
</StackLayout>
视图模型
class CreateSaleViewModel
{
// Query Variables
public string StoreQuery { get; set; }
// Query Suggestions
public ObservableCollection<Store> StoreSuggestions { get; private set; }
public ICommand SearchCmd { get; set; }
public CreateSaleViewModel()
{
SearchCmd = new Command(Search);
}
private async void Search()
{
StoreSuggestions = await App.AzureDataStore.SearchStoresAsync(StoreQuery);
}
}
答案 0 :(得分:1)
我刚遇到同样的事情。我通过完全忽略搜索命令并在代码隐藏中挂钩到AutoCompleteView TextChanged事件来解决它。
<强> XAML 强>
<controls:AutoCompleteView
x:Name="MyAutoComplete"
SuggestionItemDataTemplate="{StaticResource SuggestionItemTemplate}"
Placeholder="Type Product Here"
ShowSearchButton="True"
SearchBackgroundColor="White"
SearchTextColor = "Black"
SearchBorderColor = "Yellow"
SuggestionBackgroundColor="White"
SearchCommand="{Binding SearchCommand}"
Suggestions="{Binding Items, Mode=TwoWay}"
SelectedItem ="{Binding SelectedItem}"
SelectedCommand = "{Binding CellSelectedCommand}"/>
代码背后
public AddStockItem()
{
BindingContext = Model;
InitializeComponent();
MyAutoComplete.TextChanged += MyAutoComplete_TextChanged;
}
async void MyAutoComplete_TextChanged(object sender, TextChangedEventArgs e)
{
await Model.LoadProducts(e.NewTextValue);
}
查看模型搜索ICommand 什么都不做
public Command<string> SearchCommand
{
get
{
return _searchCommand ?? (_searchCommand = new Command<string>(
obj =>{},
obj => !string.IsNullOrEmpty(obj.ToString())));
}
}
ViewModel LoadProducts 网络呼叫后更新ObservableCollection。
public async Task LoadProducts(string term)
{
var items = await service.GetProducts(term);
Items=new ObservableCollection<string>(items);
OnPropertyChanged("Items");
}