1

I have absolutely no idea what's causing this.

Background: Using the Prism Framework

  1. I have a button bound to a DelegateCommand
  2. I call RaiseCanExecuteChanged

When I start the app in debugging mode in Visual Studio, everything works perfectly. The app runs perfectly.

When I then open the app via the .exe, the RaiseCanExecuteChanged method is not being called. I have no idea why this would be the case. Anybody else run into a similar problem?


EDIT: When I first open the app via the .exe, RaiseCanExecuteChanged is called (since I set it in the constructor of my ViewModel). However, it is never called again.


Code in case it's needed:

private readonly DelegateCommand _buttonCommand;

public ViewModel()
{
    _buttonCommand = new DelegateCommand(Button, CanExecuteButton);
}

public DelegateCommand ButtonCommand
{
    get { return this._buttonCommand; }
}

public void Button()
{
    ... do stuff ...
    _buttonCommand.RaiseCanExecuteChanged();
}

public bool CanExecuteButton()
{
    if (some condition)
        return true;
    else
        return false;
}

<Button x:Name="MyButton" Content="ClickMe"
        Command="{Binding ButtonCommand}">

I even got desperate and tried putting an IsEnabled property in my Button which I bound to CanExecuteButton ... to no avail.

Bryant
  • 355
  • 9
  • 21

2 Answers2

0

I've experienced similar issues with the Prism DelegateCommand.CanExeuteChanged event not being invoked.. By looking into the source code it looks like it is because it does not rely on the CommandManager.RequerySuggested.

Try making your own command where the event CanExecuteChanged is like so:

public RelayCommand : ICommand
{
    private event EventHandler _canExecuteChanged;
    public event EventHandler CanExecuteChanged
    {
        add
        {
            CommandManager.RequerySuggested += value;
            _canExecuteChanged += value;
        }
        remove
        {
            CommandManager.RequerySuggested -= value;
            _canExecuteChanged -= value;
        }
    }

    public void RaiseCanExecuteChanged()
    {
        var handler = _canExecuteChanged;
        if (handler != null)
            handler(this, EventArgs.Empty);

    }

    // All the other stuff also 
}

Now, if WPF detects changes in the UI then the CommandManager will invoke CanExecute on the command. And if something in the engineroom of the application changes, then you can invoke RaiseCanExecuteChanged to update CanExecute.

Anders
  • 1,590
  • 1
  • 20
  • 37
0

try

Command="{Binding DataContext.ButtonCommand,RelativeSource={RelativeSource FindAncestor, AncestorType=YourView}}" CommandParameter="{Binding}" 
Bigeyes
  • 1,508
  • 2
  • 23
  • 42