我的C#WPF MVVM应用程序中包含以下代码。
public RelayCommand PolishCommand
{
get
{
polishcommand = new RelayCommand(e =>
{
PolishedWeightCalculatorViewModel model = new PolishedWeightCalculatorViewModel(outcomeIndex, OutcomeSelectedItem.RoughCarats);
PolishedWeightCalculatorView polish = new PolishedWeightCalculatorView(model);
bool? result = polish.ShowDialog();
if (result.HasValue)
{
但是我知道,在MVVM模式中,从viewmodel调用窗口是错误的。
在下面的链接中也有说明。
M-V-VM Design Question. Calling View from ViewModel
请通过提供其他解决方案来帮助我。
提前致谢。
最佳答案
正确的是,通常不应访问 View 模型中的 View 。相反,在WPF中,我们将 View 的DataContext
属性设置为相关 View 模型的实例。有很多方法可以做到这一点。最简单但最不正确的方法是创建一个新的WPF项目,并将其放入MainWindow.xaml.cs
的构造函数中:
DataContext = this;
在这种情况下,“ View 模型”实际上是
MainWindow
“ View ”的背后代码...但是,随后将 View 和 View 模型 bundle 在一起,这就是我们尝试使用MVVM避免的方法。更好的方法是在
DataTemplate
部分的Resources
中设置关系(我更喜欢在App.Resources
中使用App.xaml
:<DataTemplate DataType="{x:Type ViewModels:YourViewModel}">
<Views:YourView />
</DataTemplate>
现在,无论您在UI中“显示” View 模型的何处,都会自动显示相关 View 。
<ContentControl Content="{Binding ViewModel}" />
第三种方法是在
Resources
部分中创建 View 模型的实例,如下所示:<Window.Resources>
<ViewModels:YourViewModel x:Key="ViewModel" />
</Window.Resources>
然后,您可以像这样引用它:
<ContentControl Content="{Binding Source={StaticResource ViewModel}}" />