[英]How to bind Windows Form Control to a “Grid” Panel using MVVM in WPF
I am attempting to use MVVM to Bind a Windows Form Control to a panel in WPF. 我正在尝试使用MVVM将Windows窗体控件绑定到WPF中的面板。 My overall objective is to be able to dynamically change which specific Windows Form Control I will use as I plan on having potentially several available.
我的总体目标是能够动态更改我计划使用的特定Windows窗体控件,因为我计划有多个可用的。
Right now, I have been able to get this to work by having the application launch a callback on initialization which accesses the grid object by name. 现在,通过让应用程序在初始化时启动一个回调(通过名称访问网格对象),我已经能够使它工作。 Here is how XAML currently looks:
XAML当前的外观如下:
<Grid Name="WindowsControlObject"></Grid>
The Callback looks like the following: 回调如下所示:
private void WindowLoaded(object sender, RoutedEventArgs e)
{
System.Windows.Forms.Integration.WindowsFormsHost host =
new System.Windows.Forms.Integration.WindowsFormsHost();
System.Windows.Forms.Control activeXControl = new SomeWindowsControl();
host.Child = activeXControl;
this.WindowsControlObject.Children.Add(host);
}
While this works, I am trying to fully utilize the MVVM pattern, as such is there a way I can do something like the following in the XAML/ModelView: 在此过程中,我正在尝试充分利用MVVM模式,因此可以在XAML / ModelView中执行以下操作:
XAML: XAML:
<Grid Content="{Binding WindowsControl"></Grid>
In my ModelView: 在我的ModelView中:
public class MyModelView
{
public Grid WindowsControl;
public MyModelView{
WindowsControl = new Grid;
System.Windows.Forms.Integration.WindowsFormsHost host =
new System.Windows.Forms.Integration.WindowsFormsHost();
System.Windows.Forms.Control activeXControl = new SomeWindowsControl();
host.Child = activeXControl;
WindowsControl.WindowsControlObject.Children.Add(host);
}
}
Am I even right in my exploration/possible approach? 我在探索/可能的方法上是否正确? It has occurred to me that I might need to use some other type of panel (other than grid), but haven't found anything obvious yet.
我想到可能需要使用其他类型的面板(网格除外),但还没有发现任何明显的东西。 If it can't be done, I have a solution, just not a very clean one.
如果无法解决,我有一个解决方案,只是不是一个很干净的解决方案。
Doing more digging, it turns out that I really wanted to bind this to a "ContentControl" tag, as follows: 进行更多的挖掘,结果发现我确实希望将其绑定到“ ContentControl”标签,如下所示:
XAML: XAML:
<ContentControl Content="{Binding WindowsControl}"/>
ViewModel: ViewModel:
private System.Windows.Forms.Control _myControl;
public WindowsFormsHost STKObject
{
get
{
return new WindowsFormsHost() { Child = _myControl};
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.