尝试将我的第一个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的datacontext解析,所以我得到一个警告,我不想要。如何让它知道它的正确类型?
答案 0 :(得分:0)
不确定这是否是最佳解决方案,仍在寻找替代方案。
使用反射:
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}"