Emixam23 Emixam23 - 1 month ago 8
C# Question

Pass a method as parameter to an XAML object

I'm currently working with a

CustomObject
that needs a
CustomObjectRenderer
for each platform.

I would like to pass a method as parameter to this object, from the XAML side, so I would be able to use this callback, from my renderer.

<control:CustomObject Callback="CallbackFunction"/>


The
CallbackFunction(object param)
is then declared in the MainPage.xaml.cs of the PCL part.

public partial class MainPage : ContentPage
{
public MainPage()
{
base.BindingContext = this;
}

public void CallbackFunction(object param)
{
Debug.WriteLine((object as Element).Name);
}
}





So, if I'm understanding well, my
CustomObject
have to be like that:

public CustomObject : Object
{
public Action<object> Callback { get; set; }
}


But I have an error about XAML parsing.. I don't get why this error is thrown..

At the end, what I want to do, it's to call this method from the renderer, and then handle things, do actions from the MainPage.xaml.cs, from the PCL part.

public class CustomObjectRenderer : ObjectRenderer
{
NativeObject nativeObject;
CustomObject customObject;

protected override void OnElementChanged(ElementChangedEventArgs<CustomObject> e)
{
base.OnElementChanged(e);

if (e.NewElement != null)
{
customObject = e.NewElement as CustomObject;
nativeObject = Control as NativeObject;
}
}

protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
}

// Etc etc ....

private void METHOD_CALLED_BY_EVENT(object o)
{
// This method get call by the renderer event and then, I want to call
// the method CallbackFunction(object); and do actions.
customObject.Callback(o as OBJECT_PARAM);
}
}


Ok, it's a bit hard for me to explain my problem to you, so if you don't understand something, let me know.

Answer

You can achieve this by using events.

MyView

public class MyView : View
{
    public event EventHandler<string> MyEvent;

    public void RaiseEvent(string parameter)
    {
        MyEvent?.Invoke(this, parameter);
    }
}

Page.xaml

<local:MyView MyEvent="MyView_OnMyEvent"></local:MyView>

Page.xaml.cs

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    private void MyView_OnMyEvent(object sender, string e)
    {
        Debug.WriteLine(e);
    }
}

Renderer

public class MyViewRenderer : ViewRenderer<MyView, SomeNativeView>
{
    private void METHOD_CALLED_BY_EVENT(string param)
    {
        Element.RaiseEvent(param);
    }
}