WPF ComboBox在Text属性更改时从数据库更新其ItemsSource

时间:2009-12-30 20:05:22

标签: wpf search combobox itemssource

我希望在表单上有一个ComboBox控件,用于在用户输入时搜索投资列表。如果我在启动时缓存数据库中的整个投资集合(目前大约有3,000个项目),我可以轻松地做到这一点,但如果没有必要,我宁愿不这样做。

我想要实现的行为是:

  • 用户在可编辑的ComboBox中键入文本。
  • 当用户输入每个字符时,会触发数据库搜索功能,每次连续按键都会缩小搜索结果。
  • 随着搜索结果的更新,下拉面板将打开并显示相关匹配项

我尝试将Text的{​​{1}}属性绑定到ComboBox上的InvestmentName(字符串)属性,以及ViewModel属性ItemsSource ComboBox InvestmentList上的ViewModel(通用列表)属性Text。执行此操作时,ItemsSource属性会从TextBox自动完成,但下拉列表显示为空。

我已经能够使用ListBox堆叠在TextBox之上来实现这些结果,但它不是很优雅,它占用了更多的屏幕空间。我已经能够使ComboBox堆叠在ComboBox之上,但IsDropDownOpen属性设置为<ComboBox Height="23" Width="260" IsSynchronizedWithCurrentItem="True" HorizontalAlignment="Left" ItemsSource="{Binding InvestmentList}" DisplayMemberPath="FullName" IsDropDownOpen="{Binding DoShowInvestmentList}" ItemsPanel="{DynamicResource ItemsTemplate}" IsEditable="True" Text="{Binding Path=InvestmentName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> 时,ViewModel会抢占焦点当有有效搜索项时,“true”。为此,使用两个控件也不太令人愉悦。

我觉得我真的很接近让它以我想要的方式工作,但有些事情让我望而却步。

此控件的XAML是:

    private bool _doShowInvestmentList;
    public bool DoShowInvestmentList
    {
        get { return _doShowInvestmentList; }
        set { if (_doShowInvestmentList != value) { _doShowInvestmentList = value; RaisePropertyChanged("DoShowInvestmentList"); } }
    }

    private List<PFInvestment> _investmentList;
    public List<PFInvestment> InvestmentList
    {
        get { return _investmentList; }
        set { if (_investmentList != value) { _investmentList = value; RaisePropertyChanged("InvestmentList"); } }
    }

    private string _investmentName;
    public string InvestmentName
    {
        get { return _investmentName; }
        set
        {
            if (_investmentName != value)
            {
                _investmentName = value;
                this.InvestmentList = DataAccess.SearchInvestmentsByName(value).ToList();

                if (this.InvestmentList != null && this.InvestmentList.Count > 0)
                    this.DoShowInvestmentList = true;
                else
                    this.DoShowInvestmentList = false;

                RaisePropertyChanged("InvestmentName");
            }
        }
    }

相关{{1}}属性为:

{{1}}

我对此做了一些研究,但我还没有找到答案。

1 个答案:

答案 0 :(得分:0)

通过我来查看关于CodeProject的这篇精彩文章:)

A Reusable WPF Autocomplete TextBox

看看Google建议示例的结尾,它类似于您所需要的,其中每个按键触发另一个查询到服务器。

相关问题