如何解决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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。