Best place to put implementation code of custom WPF command (RoutedUICommand) handlers [closed]

StackOverflow https://stackoverflow.com/questions/7796157

Вопрос

In WPF, custom commands have event handlers such as command_Executed and command_CanExecute, the best practice is that the implementation logic should not be directly implemented in the code-behind class, and it should only contain function calls to the higher level implementation logic.

While making custom commands, if there is only one function call in the handler functions of the command, it is simple to place it directly in the code-behind, but what if there are multiple function calls, or function calls returning something on the basis of which a decision is to be made (specially in the case of command_CanExecute function that is disabling/enabling a command, has to make a decision when to enable or disable a command). The possibilities I have been thinking about are following, which one is most appropriate in terms of maintainablilty, keeping code clean, software engineering principles, and best practice?

  1. Keep all the function calls and decision making statements in the code-behind (in command_execute or some function in the code-behind that command_execute calls). It is fine if code is simple, but makes things ugly when there are many handlers in the code behind. Here there is no implementation code, only decision making code that i have mentioned earlier.

  2. Keep the implementation logic in the class that defines the command and makes it accessible through static properties. Now the handler in the code-behind will only have 1 function call and will receive the return value if it has to.

  3. Implement it in the higher level classes that implement the actual functionality of the application, so that the code-behind handler has only one function call. This makes the most sense, but this option creates doubts in my mind because in some cases, the command handler may have to call methods from many different unrelated classes, so where to place that logic is difficult to decide.

  4. Any other that I have missed.

Это было полезно?

Решение

Usually I use a RelayCommand or DelegateCommand in the ViewModel (or in the Code-behind if you're not using MVVM)

private ICommand _customCommand;

public ICommand CustomCommand
{
    get
    {
        if (_customCommand == null)
        {
            _customCommand = new RelayCommand(
                CustomCommandHandler, CanCustomCommandExecute);
        }
        return _customCommand;
    }
}

private void CustomCommandHandler()
{
    // Execute Command
}

private bool CanCustomCommandExecute()
{
    // Return true/false if the command can execute or not
}

XAML:

<Button Command="{Binding CustomCommand}" />
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top