如何在 WPF 中使用 MVVM 将 Windows 窗体控件绑定到"Grid"面板



我正在尝试使用MVVM将Windows窗体控件绑定到WPF中的面板。我的总体目标是能够动态更改我将使用的特定Windows窗体控件,因为我计划有几个可用的控件。

现在,我已经能够通过让应用程序在初始化时启动一个回调来实现这一点,该回调按名称访问网格对象。以下是XAML当前的外观:

<Grid Name="WindowsControlObject"></Grid>

回调如下所示:

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);
}

虽然这是可行的,但我正在尝试充分利用MVVM模式,因为有一种方法可以在XAML/ModelView中执行以下操作:

XAML:

<Grid Content="{Binding WindowsControl"></Grid>

在我的模型视图中:

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);
    }
}

我的探索/可能的方法是否正确?我突然想到,我可能需要使用其他类型的面板(除了网格),但还没有发现任何明显的东西。如果做不到,我有一个解决方案,只是不是很干净。

做了更多的挖掘,结果发现我真的想把它绑定到一个"ContentControl"标签上,如下所示:

XAML:

<ContentControl Content="{Binding WindowsControl}"/>

ViewModel:

    private System.Windows.Forms.Control _myControl;
    public WindowsFormsHost STKObject
    {
        get 
        {
            return new WindowsFormsHost() { Child = _myControl};
        }
    }

最新更新