如何将WPF控件绑定到类方法的结果?

时间:2014-05-24 16:54:56

标签: c# wpf listbox

我正在尝试通过ViewModew将ListBox ItemSource绑定到类方法的结果。这是我的班级方法:

class MyDataProvider 
{
    public SearchResult DoSearch(string searchTerm)
    {
        return new SearchResult
        {
            SearchTerm = searchTerm,
            Results = dict.Where(item => item.Value.ToUpperInvariant().Contains(searchTerm.ToUpperInvariant())).ToDictionary(v => v.Key, v => v.Value)
        };
    } 
}   

(dict只是字符串的字典集合)

所以我有一个文本框和一个列表框。我需要在列表框中显示使用textbox文本作为searchTerm参数从myDataProvider返回的serachResult。我如何查看ViewModel?谢谢!

1 个答案:

答案 0 :(得分:1)

您的类应该实现INotifyPropertyChanged接口。正如Rohin Vats所说,你应该创建一个保存结果值的属性。

private SearchResult _myBindableProperty;
public SearchResult MyBindableProperty
{
   get { return _myBindableProperty; }
   set
      {
         if(_myBindableProperty == value)
         return;
         _myBindableProperty = value;
         RaisePropertyChanged("MyBindableProperty");
      }
}

和DoSearch方法

public void DoSearch(string searchTerm)
{
   MyBindableProperty = new SearchResult
    {
        SearchTerm = searchTerm,
        Results = dict.Where(item =>  iteem.Value.ToUpperInvariant().Contains(searchTerm.ToUpperInvariant())).ToDictionary(v => v.Key, v => v.Value)
    };


}