【问题标题】:How to use AutoCompleteBox with MVVM Light?如何将 AutoCompleteBox 与 MVVM Light 一起使用?
【发布时间】:2013-06-05 16:43:54
【问题描述】:

我正在尝试找出将 AutoCompleteBox 与 MVVM Light 结合使用的最佳方式。

    public ICommand AutoComplete
        {
            get
            {
                return new RelayCommand<KeyEventArgs>(e =>
                {
                    var txtBox = e.OriginalSource as TextBox;

                    if (e.Key == Key.Unknown)
                    {
                        return;
                    }

                    string autoComplete = txtBox.Text + e.Key;

                    if (autoComplete.Length >= 3)
                    {
                        RestClient c = new RestClient("http://localhost:3333/api/store");
                        RestRequest r = new RestRequest("/GetStoreNames",Method.GET);
                        r.AddParameter("Name", autoComplete);
                        r.AddParameter("Latitude", "49");
                        r.AddParameter("Longitude", "49");
                        var d =  c.BuildUri(r);
                        c.ExecuteAsync(r, response2 =>
                          {
                              var content = response2.Content;
                          });
                    }


                });
            }
        }


    <i:Interaction.Triggers>
                <i:EventTrigger EventName="KeyUp">
                    <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding AutoComplete, Mode=OneWay}" PassEventArgsToCommand="True"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>


<toolkit:AutoCompleteBox x:Name="acbStore" Margin="154,196,29,0" VerticalAlignment="Top" RenderTransformOrigin="0.6,0.083" Height="162" MinimumPopulateDelay="500"/>

我做了上述但有几个问题。

获得结果后,如何在自动完成区域中显示它们?

我怎样才能延迟它一次处理多个请求?如您所见,我不想在输入 3 个字符之前访问服务器,但之后这是公平的游戏。我有点担心在第一个请求返回之前会向服务器执行大约 20 个请求,从而导致带宽浪费。

【问题讨论】:

    标签: windows-phone-7 mvvm-light silverlight-toolkit


    【解决方案1】:

    我假设您正在使用KeyDown 事件或类似事件?这不是你想要的方式。相反,绑定AutoCompleteBoxPopulating 事件并将MinimumPrefixLength 上的AutoCompleteBox 设置为3,这样Populating 仅在您有3 个以上字符时才会触发。要显示在您的控件中检索到的列表,该列表需要绑定到 ItemsSource 属性,然后需要调用方法 PopulateComeplte()。

    您可以在类似的Question 上看到我的答案。

    但是,它对 MVVM 不友好,因为您需要在 AutoCompleteBox 上调用一个方法来触发控件以显示来自您的 Web 服务的列表。看看这个article 了解 MVVM 友好的方法,向下滚动到“奖励:MVVM 友好的异步过滤”部分。

    【讨论】:

    • 对不起,我以为它显示了 keyDown 事件,但我正在使用它。我会检查一下,看看情况如何。
    猜你喜欢
    • 2013-08-09
    • 2014-10-28
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    相关资源
    最近更新 更多