Xamarin 命令未在单击按钮时触发

Xamarin Command not firing on Button Click

我出于测试目的制作了一个 Xamarin 应用程序,但出于某种原因,我添加的按钮不会触发命令。我也尝试过从代码隐藏和 xaml 设置上下文,但它仍然不起作用。

XAML代码:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:implementation="clr-namespace:RxposTestApp.Implementation;assembly=RxposTestApp"
             x:Class="RxposTestApp.Page">
    <ContentPage.BindingContext>
        <implementation:BaseCommandHandler/>
    </ContentPage.BindingContext>
    <ContentPage.Content>
        <StackLayout>
            <Label Text="Welcome to Xamarin.Forms!"
                VerticalOptions="CenterAndExpand" 
                HorizontalOptions="CenterAndExpand" />
            <Button Text="CLIK MIE" Command="BaseCommand"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

BaseCommandHandler class:

public class BaseCommandHandler : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public ICommand BaseCommand { get; set; }

    public BaseCommandHandler()
    {
        BaseCommand = new Command(HandleCommand);
    }



    public void HandleCommand()
    {
       //should fire this method
    }
}
<Button Text="CLIK MIE" Command="{Binding BaseCommand}"/>

您正在使用 MVVM,因此您需要将您的属性从 ViewModel 绑定到您的视图。

所以问题是

<Button Text="CLIK MIE" Command="BaseCommand"/>

让我们退一步谈谈绑定。

<Button Text="CLIK MIE" Command="{Binding BaseCommand}"/>

您会注意到 {Binding ...},它告诉 XAML 引擎在绑定上下文中查找 public 属性。在这种情况下,我们要查找名为 "BaseCommand" 的 public 属性。绑定提供了很多东西。其中之一正在监听 属性 更改通知。

下一个问题是我们如何通知视图命令可以执行?还是目前无法执行?或者 BaseCommand 属性 设置为 ICommand 实例而不是 null?

我通常更喜欢使用私有字段来支持 public 属性。

private ICommand _baseCommand;
Public ICommand BaseCommand
{
    get
       {
           return this._baseCommand;
       }
    set
       {
           this._baseCommand = value;
           // Notification for the view. 
       }
}

通过这种方式,您可以随心所欲地发出通知,并且当 BaseCommand 的值发生变化时它总是会被发出。