首次尝试MVVM和WPF(深度学习曲线)。
在我的ViewModel中,我想运行以下代码向Mainform UI中添加一个“layoutDocument”,它是AvalonDock布局。
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);
}
上面的代码给我以下错误:
““窗口”不包含“mainPanel”的定义,也不包含“mainPanel”的扩展方法”。
请注意,在我的XAML下面,“LayoutDocumentPane”确实包含名称“mainPanel”。
我尝试将上述代码直接添加到我的MainForm View 类中(不包括Application.Current.Windows.OfType和If语句位),并且仅包括:
mainPanel.Children.Add(layoutDocument);
而且它工作正常(当我单击按钮时,在MainForm中创建了一个新的布局)。
但是,由于我想坚持使用MVVM,所以这不是一个合适的解决方案。
如何从ViewModel向MainWindow添加“layoutDocument”?提前致谢。
我的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回答问题,但它确实可以纠正编码错误。
最佳答案
这与MVVM不相关,但是要访问mainPanel
,您需要将返回的Window
转换为MainWindow
:
MainWindow mainWindow = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
if (mainWindow != null)
{
mainWindow.mainPanel.Children.Add(layoutDocument);
}
但是, View 模型不应直接访问任何窗口。这破坏了MVVM模式。
关于c# - 从ViewModel(MVVM)添加到XAML WPF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52029866/