1

在使用 FreshMvvm 制作 Xamarin Forms 应用程序时,我总是面临一个问题,即CanExecutea 的方法Command只被调用一次,并且再也不会被调用。因此,如果我一Command开始就不允许执行 's,以后就不能再允许了,反之亦然。一定有什么我做错了。

我制作了一个小型测试应用程序来演示我的代码。如果您能看一下并指出我的错误,我将不胜感激。

该应用程序非常简单;只是一个带有 aButton和 a的屏幕Switch

  • 点击按钮应显示警报。
  • 开关应切换按钮是否启用。
  • Switch 绑定到一个bool属性。
  • Button 绑定到一个Command.
  • Command的CanExecute方法返回 Switch 控制的 bool 属性的值。
  • 命令的Execute方法显示一个警报。
  • 在 PageModel 的init方法中,我将 bool 属性设置为false.

我的 MainPage.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:local="clr-namespace:FreshCommandTrial01"
             x:Class="FreshCommandTrial01.Pages.MainPage">
    <ContentPage.Content>
            <StackLayout>
            <Button
                Text="Show Alert"
                Command="{Binding ShowAlertCommand}" />
            <Switch
                IsToggled="{Binding IsAlertAllowed}" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

我的 MainPageModel.cs

using FreshMvvm;
using System.Diagnostics;
using Xamarin.Forms;

namespace FreshCommandTrial01.ViewModels
{
    public class MainPageModel : FreshBasePageModel
    {
        public override void Init(object initData)
        {
            IsAlertAllowed = false;
        }

        private bool _isAlertAllowed;
        public bool IsAlertAllowed
        {
            get { return _isAlertAllowed; }
            set
            {
                _isAlertAllowed = value;
                RaisePropertyChanged("IsAlertAllowed");
                ShowAlertCommand.ChangeCanExecute();
            }
        }

        public Command ShowAlertCommand
        {
            get
            {
                return new Command(
                  () => ShowAlertCommand_Execute(),
                  () => ShowAlertCommand_CanExecute()
                  );
            }
        }

        private bool ShowAlertCommand_CanExecute()
        {
            Debug.WriteLine("CanExecute called: IsAlertAllowed = " + IsAlertAllowed);
            return IsAlertAllowed;
        }

        private async void ShowAlertCommand_Execute()
        {
            await CoreMethods.DisplayAlert("Alert", "This is an alert", "OK");
        }
    }
}

预期行为

  • 应用程序启动时,开关处于关闭位置,按钮处于禁用状态。

  • 当我将 Switch 切换到 On 位置时,CanExecute再次调用 Command 的方法,并且 Button 变为启用状态。

观察到的行为

  • [这没问题 ] 应用启动时,Switch 处于 Off 位置,并且 Button 处于禁用状态。

  • [这不行] 当我将 Switch 切换到 On 位置时,不会调用 CanExecute,并且 Button 保持禁用状态。

我将不胜感激任何帮助。谢谢!

4

0 回答 0