dmytro.kushnir
dmytro.kushnir

Reputation: 53

How could i call child xaml method from parent in Xamarin.Forms

I need to to perform callback response in parent xaml to child xaml, and do some stuff there

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>

Child xaml.cs:

    private void NavigationBarButton_Clicked(object sender, EventArgs e)
    {
        navigationBarButton_Clicked?.Invoke(sender, e);
    }

    public void logicFunc(params)
    {
       do stuff there
    }

Parent 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"
            >
        <views:NavigationBar
            navigationBarButton_Clicked="NavigationBarButton_Clicked">
        </views:NavigationBar>
</ContentPage>

Parent xaml.cs:

    private void NavigationBarButton_Clicked(object sender, EventArgs e)
    {
        NavigationBar navbar = new NavigationBar();
        navbar.logicFunc(params); 
    }

How could i invoke response form parent to child xaml?

Upvotes: 0

Views: 1435

Answers (1)

Markus Michel
Markus Michel

Reputation: 2299

Set a defined name for your child element in the parent's xaml:

<views:NavigationBar x:Name="NavBar"
    navigationBarButton_Clicked="NavigationBarButton_Clicked">
</views:NavigationBar>

then in the method being invoked by the event handler (in the parent view), you can access the element via it's name and call the public method:

private void NavigationBarButton_Clicked(object sender, EventArgs e)
{

    NavBar.logicFunc(params); 
}

Upvotes: 1

Related Questions