'WPF Command-Canexecute-Revalidation
I've just written a little game using wpf. There is a matrix of cells I can click. The click events are working through a DelegateCommand. The problem is that the canexecute method is not called. I always have to click somewhere on the window first. I never had problems with my commandclass because I was using this:
event EventHandler ICommand.CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
I also tried to call CommandManager.InvalidateRequerySuggested(); but that also does not work. The Cells are clickable if the currentuser that is allowed to click it, is the local user of my pc(it is multiplayer). So I called InvalidateRequerySuggested after I get the Message from the network that I am the "currentplayer" now.
private void SetTurn(TurnMessage message)
{
CurrentPlayer = GetPlayer(message.PlayerID);
System.Windows.Input.CommandManager.InvalidateRequerySuggested();
}
That will have this affect:
public bool HasTurn
{
get { return CurrentPlayer != null && CurrentPlayer.PlayerID == Player.PlayerID; }
}
My Command Can-Execute looks like this:
private bool CanMatrixClick(Object param)
{
return Main.PlayerViewModel.HasTurn;
}
So has anyone a clean and easy solution for this problem? I really could not find anything which I had not tried already.
Solution 1:[1]
DelegateCommand have method RaiseCanExecuteChanged() which you can call manually to fire the CanExecute Event -
private void SetTurn(TurnMessage message)
{
CurrentPlayer = GetPlayer(message.PlayerID);
YourCommand.RaiseCanExecuteChanged();
}
Solution 2:[2]
Only for others, who get maybe into this problem: Be carefull where you call InvalidateRequerySuggested. You have to call it in the UI-Thread.
For me the dispatcher solved the problem
Application.Current.Dispatcher.BeginInvoke ((Action) (() =>
{
CommandManager.InvalidateRequerySuggested();
}));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rohit Vats |
| Solution 2 | RCP161 |
