如何在WPF中使用MVVM将Windows窗体控件绑定到“网格”面板

时间:2013-07-13 00:35:57

标签: c# .net wpf xaml mvvm

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

现在,我已经能够通过让应用程序在初始化时启动回调来实现此功能,该回调通过名称访问网格对象。以下是XAML目前的样子:

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

Callback如下所示:

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>

在我的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);
    }
}

我的探索/可能的方法是否正确?在我看来,我可能需要使用其他类型的面板(除了网格),但还没有找到任何明显的东西。如果无法做到,我有一个解决方案,而不是一个非常干净的解决方案。

1 个答案:

答案 0 :(得分:0)

进行更多挖掘,事实证明我真的想将其绑定到“ContentControl”标记,如下所示:

XAML:

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

视图模型:

    private System.Windows.Forms.Control _myControl;

    public WindowsFormsHost STKObject
    {
        get 
        {
            return new WindowsFormsHost() { Child = _myControl};
        }
    }
相关问题