我将控件绑定(bind)到DelegateCommand,并且其CanExecute部分无法正常工作。我正在使用Prism库。谁能告诉我为什么?
命令声明和实例化:
public PlayerManagementViewModel(DatabaseManager dbManager)
{
_dbManager = dbManager;
this.ResetUpToDateStatusCommand = new DelegateCommand(() => this.ResetXpUpToDateStatus());
this.DeletePlayerCommand = new DelegateCommand(() => this.DeleteSelectedPlayer(), () => SelectedPlayer != null);
this.RefreshPlayers();
}
public ICommand DeletePlayerCommand { get; private set; }
SelectedPlayer定义:
public Player SelectedPlayer
{
get { return _selectedPlayer; }
set
{
SetProperty(ref this._selectedPlayer, value);
this.OnPropertyChanged(() => this.FormattedPlayerStatus);
}
}
奇怪的是,如果您查看
DeletePlayerCommand
实例化上方的那一行,那行就可以了。我没有得到任何CanExecute
行为,但至少可以正常工作。照原样,即使没有断点,DeletePlayerCommand
命令也永远不会触发,除非我完全删除了构造函数的CanExecute部分。谁能向我解释这是为什么还是我做错了什么?
最佳答案
如果CanExecute
的DeletePlayerCommand
函数是() => SelectedPlayer != null
,则更改SelectedProperty
值时必须有一个DelegateCommandBase.RaiseCanExecuteChanged Method调用:
适当的UI元素(带有数据绑定(bind)命令)是命令调用程序。
总而言之,SelectedPlayer
属性的实现应如下更新:
class PlayerManagementViewModel : BindableBase
{
private Player _selectedPlayer;
private readonly DelegateCommand _deletePlayerCommand;
public PlayerManagementViewModel(...)
{
_deletePlayerCommand = new DelegateCommand(() => DeleteSelectedPlayer(), () => SelectedPlayer != null);
}
public ICommand DeletePlayerCommand
{
get { return _deletePlayerCommand; }
}
public Player SelectedPlayer
{
get { return _selectedPlayer; }
set
{
SetProperty(ref _selectedPlayer, value);
OnPropertyChanged(() => FormattedPlayerStatus);
_deletePlayerCommand.RaiseCanExecuteChanged();
}
}
}
关于c# - DelegateCommand.CanExecute方法行为不正确,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28226120/