Xamarin 在自定义渲染器上形成事件冒泡和调用操作

Xamarin Forms Event Bubbling and Invoking Operations on a Custom Renderer

我正在创建一个自定义 Xamarin Forms 控件,它在一个视图中包含三个按钮 (1,2,3)。为了这个例子,我们就称它为 GaugeView 吧。这是当前的设置方式:

问题是,我需要从自定义呈现器触发事件​​处理程序,因为只有本机平台控件知道何时按下了其中一个按钮。您如何将事件冒泡回 GuageView,这是共享代码所在的位置?

我正计划在自定义渲染器内部连接命令和事件处理程序,但我用了很长时间,因为事件只能从原始 class 中触发(GuageView).

有没有更好的方法来构建它?我想做的主要事情是公开平台本机 guage 并将其按钮连接起来,以便共享代码 (GuageView) 中的事件处理程序获得事件触发。

是的,您不能在声明它们的 class 之外引发事件。因此,您必须向 GaugeView 添加一个方法来引发事件。我也会让相同的方法调用命令。所以在 GaugeView

public void RaiseClick1() {
    var clicked1 = Clicked1;
    if (clicked1 != null)
        clicked1(this, EventArgs.Empty);

    if (Command1 != null && Command1.CanExecute(Command1Paramter))
         Command1.Execute(Command1Parameter);
}

然后在 GaugeViewRender 每当您需要通知视图单击按钮时:

Element.RaiseClick1();

迟到的答案,但也许是为了将来:您可以使用 IButtonController 接口从外部引发按钮的单击事件。

Xamarin.Forms.Button class 实现此接口,它提供一个方法:SendClicked

通过将呈现器 (this.Element) 中的 Xamarin.Forms 元素转换为 IButtonController,您可以调用此方法并引发 Xamarin.Forms.Button.[=11 的点击事件=]

我还创建了一个关于这个主题的博客 post:http://software.fauland.cc/?p=5637