0

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

我正在阅读他们使用的教程BindingContext = Application.Current

根据文档 Application.Current 应该返回 Application。那么上面的语句如何工作呢?

4

1 回答 1

0

首先在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;
于 2020-03-06T09:19:03.760 回答