通过将MVVM框架与Ninject一起使用,我有不同的具体ViewModel类都绑定到IViewModel接口。我的问题是要在如何确定将哪个ViewModel注入到View中的灵活性。我希望能够使用Named(string)
属性,ConstraintAttribute
或基本Attribute
来确定适当的ViewModel
换句话说,我希望所有这些返回一个单例的AlphaViewModel实例:
Bind<IViewModel>().To<AlphaViewModel>().WhenTargetHas<AlphaAttribute>();
Bind<IViewModel>().To<AlphaViewModel>().WhenMemberHas<AlphaAttribute>();
Bind<IViewModel>().To<AlphaViewModel>().WhenClassHas<AlphaAttribute>();
Bind<IViewModel>().To<AlphaViewModel>().Named("Alpha");
Bind<IViewModel>().To<AlphaViewModel>().WhenInjectedInto<AlphaView>();
我尝试过
A) Bind<IViewModel>().To<AlphaViewModel>().WhenInjectedInto<AlphaView>().InSingletonScope().Named("Alpha");
B) Bind<IViewModel>().To<AlphaViewModel>().WhenClassHas<AlphaAttribute>().InSingletonScope.Named("Alpha");
和类似的组合,但似乎使要求更加复杂。
public partial class AlphaView : Window
{
public AlphaView()
{
InitializeComponent();
}
public AlphaView([Named("Alpha")]IViewModel viewModel) : this()
{
DataContext = viewModel;
}
}
B 有更多的回旋余地,因为View可以命名为其他名称,但是仍然需要两个参数才能注入ViewModel:
[AlphaAttribute]
public partial class BravoView : Window
{
public BravoView()
{
InitializeComponent();
}
public BravoView([Named("Alpha")]IViewModel viewModel) : this()
{
DataContext = viewModel;
}
}
[AlphaAttribute]
public partial class CharlieView : Window
{
public CharlieView()
{
InitializeComponent();
}
public CharlieView(IViewModel viewModel) : this()
{
DataContext = viewModel;
}
}
public partial class CharlieView : Window
{
public CharlieView()
{
InitializeComponent();
}
public CharlieView([Named("Alpha")]IViewModel viewModel) : this()
{
DataContext = viewModel;
}
}
public partial class CharlieView : Window
{
public CharlieView()
{
InitializeComponent();
}
[AlphaAttribute]
public IViewModel AlphaVM { get; set; }
}
答案 0 :(得分:0)
这可以通过为AlphaViewModel
设置单个单例绑定来实现
Bind<AlphaViewModel>().ToSelf().InSingletonScope();
n个绑定将请求“重定向”到AlphaViewModel
,例如:
Bind<IViewModel>()
.ToMethod(ctx => ctx.Kernel.Get<AlphaViewModel>())
.WhenTargetHas<AlphaAttribute>();
...
Bind<IViewModel>()
.ToMethod(ctx => ctx.Kernel.Get<AlphaViewModel>())
.Named("Alpha");