donaldp
donaldp

Reputation: 471

How to get text from Xamarin SearchBar into viewmodel

Trying to get the text from a Xamarin Forms SearchBar into my viewmodel, and missing something, not sure what. Having read a lot of posts, I'm almost there, as intellisense generated the method for me automatically with obj as the parameter already there, but when I used it it was null, so something still missing somewhere. Here are the relevant lines of code (so if you don't see something, then assume that is what I'm missing and tell me :-) )...

MAINPAGE...
SearchBar LookupBar;

LookupBar=new SearchBar {Placeholder="Enter search term"};

vm=new Viewmodel();

LookupBar.SearchCommand = vm.TestSearchCommand;

LookupBar.SearchCommandParameter=LookupBar.Text;

VIEWMODEL...
public ICommand TestSearchCommand { get; }
(in constructor - ) TestSearchCommand=new Command<string>(TestSearch);

private void TestSearch(string obj)
{
System.Diagnostics.Debug.WriteLine(string.Format("Searchterm is {0}",obj));
}

I then type something into the search text box and press the search button, but obj coming up null. :-(

thanks,
Donald.

Upvotes: 1

Views: 1560

Answers (1)

mshwf
mshwf

Reputation: 7449

You need to set the binding, because this:

LookupBar.SearchCommandParameter=LookupBar.Text;

will always send null as it is the initial value of the LookupBar.Text when the page initialized.

Binding in code:

LookupBar.SetBinding(SearchBar.SearchCommandParameterProperty, binding: new Binding(source: LookupBar, path: "Text"));

Binding in XAML:

<SearchBar Placeholder="Enter search term" x:Name="LookupBar" SearchCommand="{Binding TestSearchCommand}" 
           SearchCommandParameter="{Binding Source={x:Reference LookupBar}, Path=Text}"/>

Upvotes: 2

Related Questions