2

I need to enable/disable a WPF button based on the return of a method.
I have a HasPermission method that tells me if the user can or not click on that button.

I've seen that I could use Command => CanExecute to avoid the execution of the action. Seen here:

How to enable/disable a button in WPF?

My question is, I have a lot of Windows in which I'll be checking for the permission, is this the best approach? Will I really have to write from 2 to N commands for every window I have?

Is there any way to make this global?
For instance, could I create the generic commands (Search/Create/...) and then only get the window it was called from and pass it to my HasPermission method?

1 Answer 1

2

You can absolutely make a static class that holds static commands, and refer to those from anywhere in your XAML.

It goes like this:

public static class GlobalCommands
{
   //ICommand can be DelegateCommand, RelayCommand... whatever floats your boat.
   public static ICommand SearchCommand { get; set; }

   //Implementation, and more static commands...
}

Then in some view:

<UserControl ...>
   ...
   <Button Content="Search" Command="{x:Static infra:GlobalCommands.SearchCommand}" />
   ...
</UserControl>

Of course, infra: is a xmlns namespace mapping to GlobalCommands' namespace.

Sign up to request clarification or add additional context in comments.

2 Comments

Got it, but how would I tell the window the button was called from? Thanks.
@eestein You'd pass it as CommandParameter. I'd make the viewmodel implement some ISearchable interface and pass that to the command.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.