Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass in an object to a Xamarin Forms custom renderer?

How can I pass an instance of some object, to a Xamarin Forms custom render?

this is the custom renderer...

public class LoginPageRenderer : PageRenderer
{
    public override void ViewDidAppear (bool animated)
    {
        ....
    }
}

and this is what I want to do.... (notice the ctor has been added ...)

public class LoginPageRenderer : PageRenderer
{
    private SomeFoo _someFoo;

    public LoginPageRenderer(MyFoo someFoo)
    {
        _someFoo = someFoo;
    }

    public override void ViewDidAppear (bool animated)
    {
        ....
    }
}

Finally, this is where this view is called (in some other part of the code).

await _navigationPage.Navigation.PushModalAsync(new LoginPage());

like image 342
Pure.Krome Avatar asked Jul 26 '15 00:07

Pure.Krome


1 Answers

If you define a publicly accessible property in your LoginPage object you can reference it in the Renderer using Element.NameOfYourProperty syntax.

Update by PureKrome

Sample code ...

LoginPage.cs (in your PCL common project).

namespace Foo
{
    public class LoginPage : ContentPage
    {
        private readonly Foo _foo;

        public LoginPage(Foo foo)
        {
            _foo = foo;
        }

        public Foo Foo { get; private set; }
    }
}

LoginPageRenderer.cs (in your iOS project)

[assembly: ExportRenderer (typeof (LoginPage), typeof (LoginPageRenderer))]

namespace Foo.iOS
{
    public class LoginPageRenderer : PageRenderer
    {
        private Foo Foo
        {
            get
            {
                var loginPage = Element as LoginPage;
                return loginPage == null
                    ? null
                    : loginPage.Foo; 
            }
        }

        public override void ViewDidAppear (bool animated)
        {
            if (string.IsNullOrWhitespace(Foo.SecretName))
            { ... }

            ...
        }
    }
}
like image 106
Will Decker Avatar answered Oct 05 '22 23:10

Will Decker