【问题标题】:How to trigger floating action button OnClicked EventHandler on Xamarin Forms如何在 Xamarin 表单中触发浮动操作按钮 OnClicked 事件处理程序
【发布时间】:2018-07-08 10:01:52
【问题描述】:

我正在使用 NuGet 包https://github.com/jamesmontemagno/FloatingActionButton-for-Xamarin.Android 来实现浮动操作按钮。我已经添加了它,但是我无法让 clicked 事件正常工作。

MyPage.xaml:

<fab:FloatingActionButtonView ImageName="settings_24.png"
                              ColorNormal="{StaticResource PrimaryColor}"
                              ColorPressed="{StaticResource PrimaryDarkColor}"
                              ColorRipple="{StaticResource PrimaryDarkColor}"
                              x:Name="FABaddTx"
                              AbsoluteLayout.LayoutFlags="PositionProportional"
                              AbsoluteLayout.LayoutBounds="1, 1, AutoSize, AutoSize"
                              Clicked="FAB_Clicked"/>

MyPage.xaml.cs:

private void FAB_Clicked(object sender, EventArgs e)
{
    var page = new AddTransactionPage();
    Navigation.PushAsync(page);
}

我发现FloatingActionButtonView.Clicked 是一个属性而不是一个事件,但是它是如何工作的呢?没有我可以使用的 ItemTappedItemSelected 事件。

我已经查看了 GitHub 存储库中提供的示例代码,遗憾的是只有 Xamarin.Android 代码,而我需要 Xamarin.Forms。

【问题讨论】:

    标签: c# xamarin.forms floating-action-button


    【解决方案1】:

    根据源存储库中的this Xamarin.Forms example,它是一个动作委托属性。

    /// <summary>
    /// Action to call when clicked
    /// </summary>
    public Action<object, EventArgs> Clicked { get; set; }
    

    Source

    您可以在页面的构造函数中设置委托。

    但是,鉴于它不是一个实际的事件处理程序,而只是一个 void 方法,如果您想安全地执行异步操作,不建议将其设为 async void 方法。

    参考Async/Await - Best Practices in Asynchronous Programming

    相反,创建一个事件和异步事件处理程序,以便可以等待异步操作

    MyPage.xaml.cs:

    public MyPage() {
        //Subscribing to our event here
        FabClicked += OnFabClicked;
        //FABaddT is already defined in the XAML so just setting the delegate here
        FABaddT.Clicked = (sender, args) => {
            //Raising the event here and passing sender and event arguments on
            FabClicked(sender, args);
        };
    }
    
    private event EventHandler FabClicked = delegate { };
    
    private async void OnFabClicked(object sender, EventArgs args) {
        var page = new AddTransactionPage();
        await Navigation.PushAsync(page);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-28
      • 1970-01-01
      • 2014-04-07
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 2013-07-26
      • 1970-01-01
      • 2011-06-18
      相关资源
      最近更新 更多