Xamarin Forms - Custom Renderer Can't Get Native Control (UWP)

1.9k views Asked by At

I have a class called RecordProvider2. It inherits from ContentView. I want to grab an instance of the native control behind the scenes. I'm not sure what that control is on UWP, but according to this article, it should be FrameworkElement (https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/custom-renderer/renderers/).

So, I wrote this custom renderer, and by all accounts, I should be able to access the native control with the "Control" property of the renderer. However, in the OnElementChanged event, the Control property is always null. What am I doing wrong?

public class RecordProvider2Renderer : ViewRenderer<RecordProvider2, FrameworkElement>
{
    protected override void OnElementChanged(ElementChangedEventArgs<RecordProvider2> e)
    {
        base.OnElementChanged(e);

        if (Control != null)
        {
        }
    }
}

Edit: As mentioned below, the renderer itself just IS the native control.

2

There are 2 answers

5
Sharada On BEST ANSWER

You can use this to get access to native control instance.

 if (e.OldElement == null)
 {
       var nativeCtrl = this;

Or, use this.ContainerElement.

EDIT 1 - Note: the above code will give access to the native container of control. Which works pretty well for ContentView; as most of the native behaviors such as gestures handling etc. can be assigned to it.

0
michael walmsley On

You need to,

SetNativeControl(new Panel())

before Control is NOT-NULL.

The panel is whatever native control you are rendering.