Ebikeneser
Ebikeneser

Reputation: 2374

BindingContext always null

I have the following xaml-

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyProj.Places"
             Title="Grid Page">
    <ContentPage.Content>
        <StackLayout>

            <SearchBar x:Name="searchBar"
           Placeholder="Enter value..."
           TextChanged="Handle_TextChanged"
           SearchCommand="{Binding SearchButtonPressed}"
           SearchCommandParameter="{Binding Source={x:Reference searchBar}, Path=Text}"/>
            <Label x:Name="LabelTextPress" Text="{Binding LabelTextPress}"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Then the associated xaml.cs -

[XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Places : ContentPage
    {
        public Places()
        {
            InitializeComponent();
        }

        void Handle_TextChanged(object sender, TextChangedEventArgs args)
        {
            var viewModel = BindingContext as Places;
            viewModel.LabelTextPress.Text = args.NewTextValue;
        }
    }

I can step into Handle_TextChanged just fine when using the searchbar, however my issue is I am unable to update the LabelTextPress because the binding isn't working.

var viewModel = BindingContext as Places; is always null, where am I going wrong with the binding of this?

Upvotes: 0

Views: 1510

Answers (1)

mm8
mm8

Reputation: 169420

The BindingContext property will return null until you actually set it to something. You can for example do this in the constructor of the ContentPage:

public Places()
{
    InitializeComponent();
    BindingContext = new YourViewModel();
}

The SearchButtonPressed property that you bind to in the XAML markup is supposed to be a property of the object (YourViewModel) that you set the BindingContext property to for the binding to work.

If you expect BindingContext as Places to return anything else than null, you should set the BindingContext to a Places instance, e.g.:

BindingContext = this;

Upvotes: 3

Related Questions