开发者

Silverlight/WPF: I Don't Want ICommand to Change Button's IsEnabled Property, Is this possible?

开发者 https://www.devze.com 2023-01-08 12:39 出处:网络
So say I have开发者_开发知识库 a button (MyButton) that binds to: public ICommand MyCommand { get; set; }

So say I have开发者_开发知识库 a button (MyButton) that binds to:

public ICommand MyCommand { get; set; }

I register this command with:

MyCommand = new DelegateCommand<object>(DoSomething);

Now if I do

MyButton.IsEnabled = false;

It doesn't do anything, i.e., the button is still enabled. I know that the command is causing this to happen because if I remove the new delegatecommand code above then the button appears disabled.

My questions are:

1. Is there a way for me to tell this binding to a command not to mess with my button's IsEnabled

2. Is there a way to change the visibility via only the commanding property (which would probably be the more correct way anyway)

Thanks!!


You need to add logic into your command for the CanExecute delegate, e.g.:

ICommand comand = new DelegateCommand<object>
    (
    executeMethod: delegate { DoSomething(); }
    ,
    canExecuteMethod: delegate { return _buttonEnabled; }
    );

_buttonEnabled = false;

CommandManager.InvalidateRequerySuggested();

_buttonEnabled = true;

CommandManager.InvalidateRequerySuggested();

The "_buttonEnabled" variable should really represent the state of your application that controls whether the button should actually be enabled or disabled. For example, it could be "_isSomethingDone" and be true\false depending on the state of your application. This would then disable your button whilst "DoSomething" is actually doing something.

Rough example:

ICommand saveCommand = new DelegateCommand<object>
    (
    executeMethod: delegate { Save(); }
    ,
    canExecuteMethod: delegate { return _canSave; }
    );

private void Save()
{
    _canSave = false;

    CommandManager.InvalidateRequerySuggested();

    //do save...

    _canSave = true;

    CommandManager.InvalidateRequerySuggested();
}


You need to use the CanExecute event of the command object, and move your logic to the command object itself. This will be checked to tell if your button is enabled. You can read msdn ICommand documentation to read further about this function. Be sure to call CanExecuteChanged() whenever something occurs that causes the status to change.

Once a button uses a command, it is bound to that. You could hide the button by changing it's visiblity still if you prefer to do that.

0

精彩评论

暂无评论...
验证码 换一张
取 消