我们如何将 Application.Current 分配给 BindingContext

How can we assign Application.Current to BindingContext

我对 xamarin 非常陌生,想知道如何使用 BindingContext。

我正在学习他们使用 BindingContext = Application.Current

的教程

根据文档 Application.Current 应该 return 应用程序。 那么上面的语句如何工作?

首先,在APp.cs中创建一个属性,实现接口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
    }
}

然后为 ContentPage BindingContext 绑定 Application.Current。

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

 this.BindingContext = Application.Current;