[我在棱镜中的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;
}
}
[ObservesCanExecuteChanged
依赖于包含观察到的属性的类的INotifyPropertyChanged
。
这会在发生更改时引发事件并因此起作用
private bool _isEnabled = true;
public bool IsEnabled
{
get { return _isEnabled; }
set { SetProperty(ref _isEnabled, value); }
}
正如您所观察到的,这不会引发任何事件并且不起作用:
public bool IsEnabled { get; set; }
我认为自动属性和属性完全相同
这完全是错误的。 “ AutoProperty”是“ Property”,但这仅涉及相似之处。从类的外部看,它们可能看起来相似,但是属性可以执行任何操作,而auto属性只是一个过于复杂的字段。