簡體   English   中英

如何從MarkupExtension返回強類型對象?

[英]How to return strongly typed object from MarkupExtension?

嘗試使我的第一個MarkupExtension作為服務定位器,並使用它來獲取XAML中的DataContext:

ViewModel和接口

public interface IMainViewModel
{
    ICommand OpenProjectCommand { get; }
}

public class MainViewModel : IMainViewModel
{
    public ICommand OpenProjectCommand { get; private set; }
    ...
}

服務定位器:

public static class ServiceLocator
{
    public static void Map<T>(object concreteType)
    {
        // store type
    }

    public static T GetInstance<T>() where T : class
    {
        // get, instantiate and return
    }
}

App.xaml中

protected override void OnStartup(StartupEventArgs e)
{
    ServiceLocator.Map<IMainViewModel>(typeof(MainViewModel));
    base.OnStartup(e);  
}

的MarkupExtension:

public class ServiceLocatorExtension : MarkupExtension
{
    public Type ServiceType { get; set; }

    public ServiceLocatorExtension(Type type)
    {
        ServiceType = type;
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (ServiceType == null)
            throw new ArgumentException("Type argument is not specified");

        var instance = ServiceLocator.GetInstance<IMainViewModel>(); // how to use this.ServiceType?
        return instance;
    }
}

XAML:

<Window ... DataContext="{loc:ServiceLocator {x:Type loc:IMainViewModel}}">
...
<Button ... Command="{Binding OpenProjectCommand}"/> // problem complains cannot resolve in datacontext type of "object"

問題:

1)如何在MarkupExtension中使用this.ServiceType屬性而不是顯式接口?

2)XAML中按鈕上的命令綁定抱怨它無法從類型為object的數據上下文中解析,因此我得到了警告,我不希望這樣做。 我如何知道它的正確類型?

不確定這是否是最佳解決方案,仍在尋找替代方案。

1:

使用反射:

public override object ProvideValue(IServiceProvider serviceProvider)
{
    if (ServiceType == null)
        throw new ArgumentException("Type argument is not specified");

    var serviceLocatorMethod = typeof(ServiceLocator).GetMethod("GetInstance").MakeGenericMethod(ServiceType);
    return serviceLocatorMethod.Invoke(null, null);
}

2:

作為設計者,這可以解決問題:

d:DataContext="{d:DesignInstance loc:MainViewModel}"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM