您是否考虑过使用接口将视图注入 ViewModel 以保持分离?我知道这会破坏 MVVM,但我已经在许多 WPF 项目中成功使用了它。我称之为 MiVVM or Model Interface-to-View ViewModel。
图案很简单。您的 Usercontrol 应该有一个接口,称为 IView。然后在 ViewModel 中你有一个带有 IMyView 类型的 setter 的属性,比如
public IMyView InjectedView { set { _injectedView = value; } }
然后在视图中创建一个名为 This
的依赖属性
public MyUserControl : IMyView
{
public static readonly DependencyProperty ThisProperty =
DependencyProperty.Register("This", typeof(IMyView), typeof(MyUserControl));
public MyUserControl()
{
SetValue(ThisProperty, this);
}
public IMyView This { get { return GetValue(ThisProperty); } set { /* do nothing */ } }
}
最后在 Xaml 中,您可以使用绑定将视图直接注入到 ViewModel 中
<MyUserControl This="{Binding InjectedView, Mode=OneWayToSource}"/>
试试吧!我已经多次使用这种模式,并且您会在启动时获得一个注入视图的接口。这意味着您保持分离(可以测试 Viewmodel,因为可以模拟 IView),但是您可以解决许多第三方控件缺乏绑定支持的问题。另外,它的速度很快。你知道绑定使用反射吗?
在上面的博客链接中有一个演示项目展示了这种模式。如果您使用第三方控件,我建议尝试 MiVVM 的 Attached Property 实现。