【发布时间】:2018-08-28 03:10:02
【问题描述】:
首次尝试 MVVM 和 WPF(陡峭的学习曲线)。 在我的 ViewModel 中,我想运行以下代码以将作为 AvalonDock 布局的“layoutDocument”添加到我的 Mainform UI 中。
ViewModel 类:
LayoutDocument layoutDocument = new LayoutDocument { Title = "Plan Layout" };
Window mainWindow = Application.Current.Windows.OfType<Window>().Where(x => x.Name == "MainWindow").FirstOrDefault();
if (mainWindow != null)
{
mainWindow.mainPanel.Children.Add(layoutDocument);
}
上面的代码给了我以下错误:
“‘Window’不包含‘mainPanel’的定义和‘mainPanel’的扩展方法”。
请注意,在下面的 XAML 中,“LayoutDocumentPane”确实包含名称“mainPanel”。
我尝试将上述代码直接添加到我的 MainForm 视图类中(不包括 Application.Current.Windows.OfType 和 If 语句位),并且只包括: mainPanel.Children.Add(layoutDocument); 它工作正常(当我单击按钮时,在我的 MainForm 中创建了一个新布局)。
但是,由于我想坚持使用 MVVM,这不是一个合适的解决方案。
如何将“layoutDocument”从 ViewModel 添加到 MainWindow?提前致谢。
我的 XAML 的摘录如下所示:
<Window x:Class="LiveExplorer.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:LiveExplorer"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
xmlns:xcad="http://schemas.xceed.com/wpf/xaml/avalondock"
xmlns:s="clr-namespace:System;assembly=mscorlib"
xmlns:vm="clr-namespace:WpfApp1.ViewModel">
<Grid> etc etc etc here---
<xcad:LayoutDocumentPaneGroup>
<xcad:LayoutDocumentPane x:Name="mainPanel">
<xcad:LayoutDocument ContentId="document1" Title="Document 1" >
<Button Content="Document 1 Content" HorizontalAlignment="Center" VerticalAlignment="Center"
Command="{Binding NewPlanCommand, Source={StaticResource viewModel}}"
/>
</xcad:LayoutDocument>
<xcad:LayoutDocument ContentId="document2" Title="Document 2">
<TextBox Text="Document 2 Content" AcceptsReturn="True"/>
</xcad:LayoutDocument>
</xcad:LayoutDocumentPane>
</xcad:LayoutDocumentPaneGroup >
编辑:
虽然接受的答案没有根据 MMVM 回答问题,但它确实纠正了编码错误。
【问题讨论】:
-
从视图模型向 UI 组件添加子控件不是 MVVM 模式。视图模型不应该知道视图的组件。如果要添加多个视图模型或视图模型的属性,您应该在 xaml 中将数据绑定到集合。