该命令在 Xamarin Prism 中启用按钮

The Command enables the Button in Xamarin Prism

我正在使用 Xamarin Prism,我试图禁用该按钮,但每当我添加它启用的命令时。这是什么?

代码:

<Button       
  Command="{Binding save}"
  IsEnabled="False"/>

document of Button.Command Property可以看出:

This property is used to associate a command with an instance of a button. This property is most often set in the MVVM pattern to bind callbacks back into the ViewModel. IsEnabled is controlled by the Command if set.

因此,如果您不设置命令 属性,它将正常工作。

如果设置命令 属性,isEnable 由命令本身控制。

这里我写了一个例子来告诉大家如何在命令中控制按钮的启用属性:

在xaml中:

<ContentPage.BindingContext>
    <local:CommandDemoViewModel />
</ContentPage.BindingContext>

<StackLayout>
    <Button Text="Divide by 2"
            VerticalOptions="CenterAndExpand"
            HorizontalOptions="Center"
            Command="{Binding DivideBy2Command}"  
            />
</StackLayout>

和视图模型:

class CommandDemoViewModel : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;

    public Command DivideBy2Command { private set; get; }

    public CommandDemoViewModel()
    {
        DivideBy2Command = new Command(()=> performCommandAction(), ()=>isButtonEnable());
    }

    private bool isButtonEnable()
    {

        //Handle the if the button isEnable here
        //Reture ture or false with your own logic here to control the button's isEnabled

        return false;
    }


    private void performCommandAction()
    {
        //Handle the button click logic here 
    }

}

使用构造函数public Command(Action execute, Func<bool> canExecute);.

您可以通过命令的CanExecute来控制isEnable。在方法 isButtonEnable 中用自己的逻辑返回 ture 或 false 来控制按钮的 isEnabled.