Is injecting commands via markup extension a good practice?

1.1k views Asked by At

I have a custom markup extension which resolve commands using dependency injection. It is very handy for me, because I don't have to create commands in view model and bindings for them. Recently I've been told that using such markup extension isn't a good practice in mvvm and I should avoid that. Is that true?

Code of markup extension:

public class InjectCommandExtension : MarkupExtension
{
    #region Props
    [ConstructorArgument("key")]
    public string Key { get; set; }
    #endregion

    #region ctor
    public InjectCommandExtension()
    {
    }

    public InjectCommandExtension(string key)
    {
        Key = key;
    }
    #endregion

    #region ProvideValue
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (Key == null)
            throw new ArgumentNullException("Key");

        return ServiceLocator.Current.GetInstance<ICommand>(Key);
    }
    #endregion
}

Use in XAML:

<Button Content="Delete" Command="{mext:InjectCommand DeleteOrderCommand}"/>
2

There are 2 answers

0
Tigran On

Personally don't see, if we speak in this general way, about custom markup injection. The only thing I can cancern about is the complexity you should dela with. Having them decalred in XAML help you and other developers in the group to avoid creating a mess.

Good luck.

0
The Angry Programmer On

I would keep them in the ViewModel, that way you can test the commands. The main reason for MVVM is testability of the UI. The XAML should be restricted for UI behaviour and styling and logic (such as the executing of commands), should be in the ViewModel.