简体   繁体   中英

If I use ContentPage.BindingContext in XAML to define my binding context then how do I access that in the C# back end?

In my XAML I define the binding context like this:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             xmlns:local="clr-namespace:Japanese;assembly=Japanese" 
             xmlns:template="clr-namespace:Japanese.Templates" 
             xmlns:viewModels="clr-namespace:Japanese.ViewModels; assembly=Japanese"
             x:Class="Japanese.Cards" Title="{Binding Title}">
    <ContentPage.BindingContext>
        <viewModels:CardsViewModel />
    </ContentPage.BindingContext>
</ContentPage>

What I would like to know is how can I access this context in my C# back end.

public partial class Cards : ContentPage
{

    public Cards()
    {
        InitializeComponent();
        NavigationPage.SetBackButtonTitle(this, "Back");
    }

    protected override void OnAppearing()
    {
        // I want to set some properties of the view here

It seems you cannot give it an x:Name attribute like other elements in your XAML. In that case, your options are limited to declaring the object for your binding context in the code-behind, or referencing it from the BindingContext property.

For the latter approach, do it like this:

protected override void OnAppearing()
{
    var cardsViewModel = BindingContext as CardsViewModel;

    if (cardsViewModel == null)
        return;

    cardsViewModel.Property = Value;
}

Earlier answer for reference:

You should be able to give it a name like so:

<ContentPage.BindingContext>
    <viewModels:CardsViewModel x:Name="cardsViewModel" />
</ContentPage.BindingContext>

This will effectively just create a declaration like this in generated code:

private CardsViewModel cardsViewModel;

You can now access it in your code-behind:

protected override void OnAppearing()
{
    cardsViewModel.Property = Value;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM