赢得8.1 SearchBox - 绑定建议

时间:2013-11-20 09:55:28

标签: windows-runtime winrt-xaml

我们正在编写一个使用新的SearchBox XAML控件的Windows 8.1商店应用程序。它似乎是将建议输入下拉列表的唯一方法,因为用户键入的是使用SearchBoxSuggestionsRequestedEventArgs并从事件中获取SearchSuggestionCollection,然后将建议附加到该列表。

我们正在使用Prism for WinRT,并希望从获取建议字符串列表的ViewModel中分离SearchBox及其事件。

我无法找到将字符串列表绑定到SearchSuggestionCollection或以编程方式添加它们的任何方式,这些方法不涉及使用事件args,这使得单元测试变得非常复杂。

有没有办法绑定/添加不涉及事件参数的建议?

1 个答案:

答案 0 :(得分:8)

好的,所以我对这个问题很着迷,这里是使用SearchBox的解决方案。我已在MSDNGitHub

上传了完整的示例

简而言之,使用Behavior SDK和InvokeCommand,然后使用转换器通过使用新属性InputConvert和InputConverterParameter来获取所需的任何数据。

XAML:

    <SearchBox SearchHistoryEnabled="False" x:Name="SearchBox" Width="500" Height="50">
        <SearchBox.Resources>
            <local:SearchArgsConverter x:Name="ArgsConverter"/>
        </SearchBox.Resources>
        <interactivity:Interaction.Behaviors>
            <core:EventTriggerBehavior EventName="SuggestionsRequested">
                <core:InvokeCommandAction
                    Command="{Binding SuggestionRequest}"
                    InputConverter="{StaticResource ArgsConverter}"
                    InputConverterLanguage="en-US"
                    InputConverterParameter="{Binding ElementName=SearchBox, Path=SearchHistoryEnabled}"/>
            </core:EventTriggerBehavior>
        </interactivity:Interaction.Behaviors>
    </SearchBox>

转换器:

 public sealed class SearchArgsConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var args = (SearchBoxSuggestionsRequestedEventArgs)value;
        var displayHistory = (bool)parameter;

        if (args == null) return value;
        ISuggestionQuery item = new SuggestionQuery(args.Request, args.QueryText)
        {
            DisplayHistory = displayHistory
        };
        return item;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return value;
    }
}

Mainpade codebehind - 当然你想在VM中使用它:)

 public sealed partial class MainPage
{
    public DelegateCommand<string> Search { get; set; }
    public DelegateCommand<ISuggestionQuery> SuggestionRequest { get; set; }

    public MainPage()
    {
        InitializeComponent();
        Search = new DelegateCommand<string>(SearchedFor, o => true);
        SuggestionRequest = new DelegateCommand<ISuggestionQuery>(SuggestionRequestFor, o => true);

        DataContext = this;
    }

    private void SuggestionRequestFor(ISuggestionQuery query)
    {
        IEnumerable<string> filteredQuery = _data
            .Where(suggestion => suggestion.StartsWith(query.QueryText,
                StringComparison.CurrentCultureIgnoreCase));
        query.Request.SearchSuggestionCollection.AppendQuerySuggestions(filteredQuery);
    }

    private readonly string[] _data = { "Banana", "Apple", "Meat", "Ham" };

    private void SearchedFor(string queryText)
    {
    }
}

我在博客上写了一篇完整的文章,但以上就是你真正需要的:)