因此,我对WPF和MVVM非常陌生,虽然我理解前提,但这些东西中的许多东西就像是试图为我读取象形文字。
基本上,我的情况是这样的:我使用的是Activiz,一个用于VTK的c#包装器,它是一个图像处理/可视化库。因此,在这个库中,有一个名为vtk:RenderWindowControl的WinForms控件,它是一个包含处理所有可视化功能的类的opengl控件。我认为只使用WinForms会更简单,但这对我来说并不是一个真正的选择。
因此,要在WPF应用程序中使用vtk:RenderWindowControl,我只需要将其放入WindowsFormsHost中,然后就可以在后面的代码中使用它,就像example code一样(如果这是.xaml.cs文件的正确术语)
这对于测试应用程序来说是很好的,但在实践中,如果可能的话,我想遵循MVVM。这就是我撞到墙的地方。如果"renderControl“位于View类中,我如何在ViewModel中引用和使用它?我认为绑定是这个问题的答案,但我只知道如何为简单的类型和命令做这件事。
遵循我在另一个线程中找到的想法,我设法设置了类似this answer的东西
我的代码是这样的:
public partial class RenderPanel_View : UserControl
{
public static readonly new DependencyProperty RWControlProperty =
DependencyProperty.Register("RWControl", typeof(RenderWindowControl), typeof(RenderPanel_View), new PropertyMetadata(null));
public RenderWindowControl RWControl
{
get { return (RenderWindowControl)GetValue(RWControlProperty); }
set { SetValue(RWControlProperty, value); }
}
public RenderPanel_View()
{
// This is necessary to stop the rendercontrolwindow from trying to load in the
// designer, and crashing the Visual Studio.
if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this)) {
this.Height = 300;
this.Width = 300;
return;
}
InitializeComponent();
this.RWControl = new RenderWindowControl();
this.RWControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.WFHost.Child = this.RWControl;
}
}
我的.xaml看起来像这样
<UserControl x:Class="vtkMVVMTest.RenderPanel.RenderPanel_View"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:vtk="clr-namespace:Kitware.VTK;assembly=Kitware.VTK"
xmlns:rp="clr-namespace:vtkMVVMTest.RenderPanel"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
RWControl="{Binding VMControlProperty}">
<Grid>
<WindowsFormsHost x:Name ="WFHost"/>
</Grid>
</UserControl>
所以有两件事。其一,xaml头的最后一行是错误的,“成员'RWControl‘无法识别或访问”。我真的不明白为什么。其次,我猜是等式中ViewModel的一半,VMControlProperty应该如何定义?
至少我是在正确的轨道上,还是这条路走错了?
发布于 2014-06-22 21:33:00
一些控件不是MVVM友好的,你必须让ViewModel意识到视图界面,并允许直接与之交互。不要向ViewModel开放整个控件,这将破坏编写测试的能力,将接口放在顶部,例如IRenderPanelView,并在接口中只打开您需要从ViewModel访问的功能。然后,您可以在视图中创建此类型的DP属性,在构造函数中设置它,并将其绑定到xaml中的ViewModel.View属性。
https://stackoverflow.com/questions/24355868
复制