简体   繁体   中英

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

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.

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.

You need to,

SetNativeControl(new Panel())

before Control is NOT-NULL .

The panel is whatever native control you are rendering.

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