简体   繁体   中英

How to bind to a custom event handler in XAML

I am having some difficulty figuring out how to properly bind a custom event handler from my XAML instead of my code behind. In my code behind I current have this in my parent code behind:

this.stepBar.Callback = SetViewForStep;

This works fine and it will properly set the Callback event handler in my custom control which is defined as follows:

public static readonly BindableProperty CallbackProperty = BindableProperty.Create(nameof(Callback), typeof(EventHandler), typeof(StepProgressBarControl), null);

public EventHandler Callback {
            get {
                return (EventHandler)GetValue(CallbackProperty);
            } set {
                SetValue(CallbackProperty, value);
            }
        }

However, I would like to be able to define it purely in XAML the same way one might define a Click event on a button.

<StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
                     Padding="20" Spacing="20">
            <customcontrols:StepProgressBarControl 
                StepColor="LightPink" 
                Steps="5" 
                Callback="SetViewForStep"
                StepSelected="{Binding SelectedStep}" x:Name="stepBar" />
            <Label
               Text="{Binding SelectedStep, StringFormat='The Step Selected is {0}'}"
               FontAttributes="Bold"
               FontSize="Large"
               HorizontalOptions="Center"
               VerticalOptions="CenterAndExpand" />
        </StackLayout>

However, if I define it in the XAML and try to run it I get a compile error of Error XFC0009 No property, BindableProperty, or event found for "Callback", or mismatching type between value and property.

How can I create an EventHandler such that I can define its function in my xaml.cs the same way one might define a click event for a button or any other built in control that has an exposed EventHandler property?

Declaring Callback as event should be able to solve the problem.

Change your code in custom control as below

 public event EventHandler Callback;

In this way when we type Callback in xaml, the intellisense helps us to reference the method in page.

在此处输入图像描述

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