ericpap
ericpap

Reputation: 2937

How can i bind a WPF control to the result of a class method?

I'm trying to bind a ListBox ItemSource to the result of a class method via ViewModew. This is my class method:

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 is just a dictionary collection of strings)

So i have a textbox and a listbox. I need to show on the listbox the serachResult returned from myDataProvider using textbox text as searchTerm Parameter. How can i do that view ViewModel? Thanks!

Upvotes: 0

Views: 145

Answers (1)

partyelite
partyelite

Reputation: 892

Your class should implement INotifyPropertyChanged interface. As Rohin Vats stated, you should create a property which will hold the result value.

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

and in the DoSearch method

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)
    };


}

Upvotes: 1

Related Questions