Alan2
Alan2

Reputation: 24562

How can I make a template call a method?

I have this template:

<?xml version="1.0" encoding="utf-8"?>
<ViewCell xmlns="http://xamarin.com/schemas/2014/forms" 
          xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
          x:Class="Japanese.OpenPageTemplate"
          x:Name="this">
        <Label Text="ABC" VerticalTextAlignment="Center" />
 </ViewCell>

and the code behind:

using System;
using System.Collections.Generic;
using Xamarin.Forms;

namespace Japanese.Templates
{
    public partial class OpenPageTemplate : ViewCell
    {
        public OpenPageViewCellTemplate()
        {
            InitializeComponent();
        }

        protected override void OnTapped()
        {
            base.OnTapped();
            // I need to call openPage() here or at least have openPage() called from the place where the template is used.
        }
    }
}

Can someone tell me how I can make this template call a method called openPage() when the user taps on the ViewCell? In a previous question there was an answer about using the .Invoke method that went something like this:

ClickAction?.Invoke(this, new EventArgs());

However this time there's just one action to invoke and I don't need to pass information on the action into ClickAction.

Upvotes: 3

Views: 217

Answers (2)

Ben
Ben

Reputation: 2985

Wrap the ViewCell in a DataTemplate:

<?xml version="1.0" encoding="utf-8" ?>
<DataTemplate xmlns="http://xamarin.com/schemas/2014/forms"
          xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
          xmlns:template="clr-namespace:Japanese"
          x:Class="Japanese.OpenPageTemplate">
  <ViewCell Tapped="OnOpenPageTapped">
    ...
  </ViewCell>
</DataTemplate>

Codebehind:

namespace Japanese
{
  public partial class OpenPageTemplate : DataTemplate
  {
    public OpenPageTemplate ()
    {
        InitializeComponent ();
    }

    private void OnOpenPageTapped(object sender, EventArgs e)
    {
        //example: template is an itemtemplate for a list of class A.B with property C
        var c = ((sender as ViewCell)?.BindingContext as A.B)?.C;
    }
    ...

Upvotes: 2

Nkosi
Nkosi

Reputation: 247018

Subscribe to the desired Cell.Tapped Event and invoke the action when the event is raised.

XAML

<template:OpenPageTemplate Tapped="OnOpenPageTapped" />

Code behind

private void OnOpenPageTapped(object sender, EventArgs args) {
    openPage();
}

assuming that openPage() is accessible from the place where the template is used.

Upvotes: 2

Related Questions