![](/img/trans.png)
[英]How to return a strongly-typed object from a SubSonic SPROC call with SPROC parameters?
[英]How to return strongly typed object from MarkupExtension?
嘗試使我的第一個MarkupExtension作為服務定位器,並使用它來獲取XAML中的DataContext:
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
}
}
protected override void OnStartup(StartupEventArgs e)
{
ServiceLocator.Map<IMainViewModel>(typeof(MainViewModel));
base.OnStartup(e);
}
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;
}
}
<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的數據上下文中解析,因此我得到了警告,我不希望這樣做。 我如何知道它的正確類型?
不確定這是否是最佳解決方案,仍在尋找替代方案。
使用反射:
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);
}
作為設計者,這可以解決問題:
d:DataContext="{d:DesignInstance loc:MainViewModel}"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.