0

我正在尝试找出将 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 个请求,从而导致带宽浪费。

4

1 回答 1

1

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

你可以在这里看到我对类似问题的回答。

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

于 2013-06-06T01:55:32.543 回答