Xamarin SearchBar Tip 2 – search as you type

See part one on how to pass the text that was typed in passed to the command.

This next tip runs the search command when the text changes, as you type.

Add a new behaviour, I added this to a subfolder “Behaviour”

<br />
public class TextChangedBehavior: Behavior&lt;SearchBar&gt;<br />
{<br />
    protected override void OnAttachedTo(SearchBar bindable)<br />
    {<br />
        base.OnAttachedTo(bindable);<br />
	bindable.TextChanged += Bindable_TextChanged;<br />
    }</p>
<p>    protected override void OnDetachingFrom(SearchBar bindable)<br />
    {<br />
        base.OnDetachingFrom(bindable);<br />
	bindable.TextChanged -= Bindable_TextChanged;<br />
    }</p>
<p>    private void Bindable_TextChanged(object sender, TextChangedEventArgs e)<br />
    {<br />
	((SearchBar)sender).SearchCommand?.Execute(e.NewTextValue);<br />
    }<br />
}<br />

Then in the view add a new xmlns

</p>
<p>xmlns:behaviours=&quot;clr-namespace:MyTestApp.Behaviours&quot;</p>
<p>

And add the behaviour like so

<br />
&lt;SearchBar x:Name=&quot;MySearchBar&quot; SearchCommand=&quot;{Binding SearchCommand}&quot; SearchCommandParameter=&quot;{Binding Text, Source={x:Reference MySearchBar}}&quot;&gt;<br />
    &lt;SearchBar.Behaviors&gt;<br />
        &lt;behaviours:TextChangedBehavior /&gt;<br />
    &lt;/SearchBar.Behaviors&gt;<br />
&lt;/SearchBar&gt;<br />

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.