Mando
Mando

Reputation: 11722

SearchBar.IsEnabled binding are not updated when property changed in Xamarin.Forms

I want to disable searchbar whenever my viewmodel is busy. And I have the following xaml for my view (part of view):

<SearchBar x:Name="searchBar" TextChanged="OnSearchQueryChanged" Grid.Row="0"  IsEnabled="{Binding IsBusy}"/>
<ActivityIndicator x:Name="progress" IsRunning="{Binding IsBusy}" IsVisible="{Binding IsBusy}"/>

Both elements are bound to the the same property however SearchBar stays disabled when my ViewModel raise IsBusy = false. Same time progress becomes hidden.

What could be wrong here?

Upvotes: 1

Views: 2470

Answers (1)

Stephane Delcroix
Stephane Delcroix

Reputation: 16232

What you want is to set the SearchBar.IsEnabled property to true when you view model IsBusy property is false, and vice versa.

What you're doing right now, is disabling (setting IsEnabled to false) the search bar when the your vie model is no longer busy (IsBusy is false).

You need a converter for this, one that returns true for false, and false for true:

public class NotConverter:IValueConverter
{
    public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value.GetType () == typeof(bool))
            return !((bool)value);
        return value;
    }

    public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException ();
    }
}

In order to use it in your binding in xaml, let's include an instance of it as a resource in the container wrapping your xaml snippet (let's assume it's a ContentPage), and then we can reference that converter in the {Binding} markup extension:

<ContentPage 
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:YourNamespace;assembly=YourAssemblyName">
    <ContentPage.Resources>
        <ResourceDictionary>
            <local:NotConverter x:Key="notConverter"/>
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Content>
        <StackLayout Orientation="Vertical">
            <SearchBar x:Name="searchBar" TextChanged="OnSearchQueryChanged" Grid.Row="0"  IsEnabled="{Binding IsBusy, Converter={StaticResource notConverter}}"/>
            <ActivityIndicator x:Name="progress" IsRunning="{Binding IsBusy}" IsVisible="{Binding IsBusy}"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Upvotes: 6

Related Questions