如何使模板调用方法?

时间:2018-07-16 11:00:49

标签: xamarin xamarin.forms

我有这个模板:

<?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>

及其背后的代码:

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.
        }
    }
}

有人可以告诉我当用户点击ViewCell时如何使此模板调用称为openPage()的方法吗?在上一个问题中,有一个关于使用.Invoke方法的答案,该方法如下所示:

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

但是这次只有一个动作要调用,我不需要将有关该动作的信息传递给ClickAction。

2 个答案:

答案 0 :(得分:2)

订阅所需的Cell.Tapped Event并在引发事件时调用操作。

XAML

<template:OpenPageTemplate Tapped="OnOpenPageTapped" />

后面的代码

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

假定可以从使用模板的位置访问openPage()

答案 1 :(得分:2)

将ViewCell包裹在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>

隐藏代码:

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;
    }
    ...