如何在Xamarin Forms中从父项调用子项xaml中的方法?

时间:2018-07-05 13:14:15

标签: c# xaml xamarin xamarin.forms

我需要执行一个xaml的继承,并触发child的调用。 儿童xaml:

<?xml version="1.0" encoding="UTF-8"?>
    <ContentView xmlns="http://xamarin.com/schemas/2014/forms" 
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="project.NavigationBar">
        <ContentView.Content>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>

                    <StackLayout 
                        Orientation="Horizontal"
                        Grid.Column="0"
                        HorizontalOptions="CenterAndExpand"
                        VerticalOptions="End">
                        <Button
                            x:Name="NavigationBarButton" 
                            Clicked="NavigationBarButton_Clicked" 
                            Text="Gallery">
                        </Button>
                    </StackLayout>
                </Grid>
        </ContentView.Content>
    </ContentView>

孩子xaml.cs:

        private void NavigationBarButton_Clicked(object sender, EventArgs e)
        {
        }

父母xaml:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="project.main"
             xmlns:views="project.NavigationBar"
            >
    <StackLayout>
                <views:NavigationBar/>
    </StackLayout>
</ContentPage>

父项xaml.cs:

    private void NavigationBarButton_Clicked(object sender, EventArgs e)
    {
       Get call from child there and do my logic
    }

我该如何触发孩子的点击通话并将其扔给父母?

1 个答案:

答案 0 :(得分:3)

首先在您的CustomView中创建一个EventHandler:

public event EventHandler myClickEvent;

然后,添加要调用的函数(仍在customView中:

void myClickEvent(object sender, EventArgs e)
{
    myClickEvent?.Invoke(sender, e);
}

在页面中,将方法绑定到您的视图,该视图将被称为:

  <views:NavigationBar myClickEvent="MyClickEvent"/>

在您的page.xaml.cs中:

void MyClickEvent(object sender, EventArgs e)
    {
        //handle method here
    }