gpt4 book ai didi

c# - DelegateCommand.CanExecute 方法行为不正确

转载 作者:太空宇宙 更新时间:2023-11-03 20:01:05 25 4
gpt4 key购买 nike

我将控件绑定(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 部分。

任何人都可以向我解释为什么这是或我做错了什么吗?

最佳答案

如果 DeletePlayerCommandCanExecute 函数是 () => SelectedPlayer != null,那么必须有一个 DelegateCommandBase.RaiseCanExecuteChanged MethodSelectedProperty 值改变时调用:

Raises CanExecuteChanged on the UI thread so every command invoker can requery to check if the command can execute.

适当的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com