通过标记扩展注入命令是一种好的实践吗?

3

我有一个自定义的标记扩展,它使用依赖注入来解析命令。这对我非常方便,因为我不必在视图模型中创建命令和绑定它们。

最近有人告诉我,在mvvm中使用这样的标记扩展并不是一个好习惯,我应该避免使用它。这是真的吗?

标记扩展的代码:

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
}

在XAML中使用:

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

2
你能展示一下你的ViewModel和XAML的代码吗?我非常想看看它们是如何连接的。 - blindmeis
你在哪里和何时进行注入?这将影响它是否是良好的实践。 - Esoteric Screen Name
2个回答

0

就个人而言,我并不认为我们需要谈论关于自定义标记注入的问题。我唯一担心的是你可能需要处理的复杂性。在XAML中声明它们可以帮助你和其他开发人员避免创建混乱。

祝好运。


0

我建议将它们放在ViewModel中,这样你就可以测试命令。MVVM的主要原因是为了UI的可测试性。XAML应该限制于UI行为和样式,逻辑(如命令的执行)应该在ViewModel中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接