Xamarin表单无法将命令分配给自定义按钮

问题描述

我有问题。我正在使用以下代码https://github.com/Polarts/CrossFAB

<c:FloatingMenu Margin="0,10,10" BGColor="#56D7A5" OpenIcon="openFab_icon" CloseIcon="closeFab_icon" AbsoluteLayout.LayoutBounds=".95,.95" AbsoluteLayout.LayoutFlags="PositionProportional"> <c:FloatingButton x:Name="btnAddItem" BGColor="#59E1FF" IconSrc="add_item_icon" BindingContext="{x:Reference ItemPage}" OnClickCommand="{Binding btnAdditemcommand}" /> </c:FloatingMenu> 中,我像这样添加了FabMenu:

public partial class Page1 : ContentPage
{

    public static ICommand btnAdditemcommand { get; set; }

    public Page1 ()
    {
        InitializeComponent();
            
        btnAdditemcommand = new Command(OpenNewItemPage);
    }

    private async void OpenNewItemPage()
    {
        await Application.Current.MainPage.Navigation.PushAsync(new NewItemPage());
    }
}

在page1.xaml.cs中,我添加了如下命令:

FloatingButton.xaml.cs

问题是,当我单击按钮时,在OnClickCommand.Execute(null);行的OnClickCommand中给出了错误错误是:

对象引用未设置为对象的实例

这是因为根据我的代码{{1}}未设置为实例,因此其值为null。 可以在以下位置找到FloatingButton.xaml.cs的代码https://github.com/Polarts/CrossFAB/blob/master/CrossFAB/Controls/FloatingButton.xaml.cs

我该如何解决

解决方法

我认为您没有成功绑定命令。

在.cs中,设置BindingContext = this;并且不要将btnAddItemCommand定义为静态属性:

public partial class MainPage : ContentPage
{
    public ICommand btnAddItemCommand { get; set; }

    public MainPage()
    {
        InitializeComponent();

        btnAddItemCommand = new Command(OpenNewItemPage);

        BindingContext = this;
    }
    private void OpenNewItemPage()
    {
        Console.WriteLine("OpenNewItemPage");
    }
}

在xaml中,删除bindingContext部分:

<StackLayout>
    <!-- Place new controls here -->
    <Button x:Name="btnAddItem" Text="test" Command="{Binding btnAddItemCommand}" />

</StackLayout>