How can we assign Application.Current to BindingContext

630 views Asked by At

Iam very much new to xamarin and wondering about how BindingContext is used.

I was going through a tutorial wherein they used BindingContext = Application.Current

according to the docs Application.Current should return Application. so how can this above statement work?

1

There are 1 answers

0
Cherry Bu - MSFT On BEST ANSWER

Firstly, create one property in APp.cs, implement interface INotifyPropertyChanged.

 public partial class App : Application, INotifyPropertyChanged
{
    private string _str;
    public string str
    {
        get { return _str; }
        set
        {
            _str = value;
            RaisePropertyChanged("str");
        }
    }
    public App()
    {
        InitializeComponent();
        str = "this is test";
        MainPage = new NavigationPage(new simplecontrol.Page26());         
    }


    public event PropertyChangedEventHandler PropertyChanged;      
    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    protected override void OnStart()
    {
        // Handle when your app starts
    }

    protected override void OnSleep()
    {
        // Handle when your app sleeps
    }

    protected override void OnResume()
    {
        // Handle when your app resumes
    }
}

Then binding Application.Current for ContentPage BindingContext.

<ContentPage.Content>
    <StackLayout>
        <!--<local:View2 Items="{Binding modelas}" />-->
        <Label
            HorizontalOptions="CenterAndExpand"
            Text="{Binding str}"
            VerticalOptions="CenterAndExpand" />
    </StackLayout>
</ContentPage.Content>

 this.BindingContext = Application.Current;