首页 > 解决方案 > AutoProperties 不适用于棱镜中的 DelegateCommand.ObservesCanExecute?

问题描述

在 prism 中的 DelegateCommand 上的 ObservesCanExecute 有一些我不理解的东西。AutoProperties 可以看到一些东西......我认为

我有一个带有按钮的视图,该按钮绑定到我的视图模型中的 DelegateCommand。出于某些原因,在我看来,我像这样捕获 CanExecuteChanged 事件:

MyButton.Command.CanExecuteChanged += Command_CanExecuteChanged;

问题是,在我的视图模型中,当我使用自动属性声明 IsEnabled 时,视图中的事件不会被触发。就像 ObservesCanExecute 不再起作用一样。正常吗?有什么我做错了吗?我认为 AutoProperties 和 Properties 完全一样......这是我的 ViewModel :

public class MainPageViewModel : ViewModelBase
{
    // VERSION 1 - It Works
    private bool _isEnabled = true;
    public bool IsEnabled
    {
        get { return _isEnabled; }
        set { SetProperty(ref _isEnabled, value); }
    }

    // VERSION 2 - Don't works
    // public bool IsEnabled {get; set; } = true;

    public DelegateCommand MyCommand { get; set; } = null;

    public MainPageViewModel(INavigationService navigationService)
        : base(navigationService)
    {
        Title = "Main Page";
        MyCommand = new DelegateCommand(Execute).ObservesCanExecute(() => IsEnabled);
    }

    private void Execute()
    {
        IsEnabled = !IsEnabled;
    }
}

标签: xamarinpropertiescommandprismdelegatecommand

解决方案


ObservesCanExecuteChanged依赖于INotifyPropertyChanged包含观察到的属性的类。

这会在发生更改的情况下引发事件并因此有效

private bool _isEnabled = true;
public bool IsEnabled
{
    get { return _isEnabled; }
    set { SetProperty(ref _isEnabled, value); }
}

虽然这不会引发任何事件并且不起作用,但正如您所观察到的:

public bool IsEnabled { get; set; }

我以为 AutoProperties 和 Properties 完全一样

那是完全错误的。“AutoProperty”是“Property”,但其相似之处仅此而已。从类的外部看,它们可能看起来很相似,但属性可以做任何事情,而自动属性只是一个过于复杂的字段。


推荐阅读