【问题标题】:How to bind Windows Form Control to a "Grid" Panel using MVVM in WPF如何在 WPF 中使用 MVVM 将 Windows 窗体控件绑定到“网格”面板
【发布时间】:2013-07-13 00:35:56
【问题描述】:

我正在尝试使用 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: ViewModel: public MyModelView { 私有 System.Windows.Forms.Control _myControl;公共 WindowsFormsHost STKObject { get { return new WindowsFormsHost() { Child = _myControl}; } } }
  • 不太明白您的问题,您想使用绑定将host 控件添加到您的Grid 吗?

标签: c# .net wpf xaml mvvm


【解决方案1】:

多挖了一下,原来是真的想把这个绑定到一个“ContentControl”标签上,如下:

XAML:

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

视图模型:

    private System.Windows.Forms.Control _myControl;

    public WindowsFormsHost STKObject
    {
        get 
        {
            return new WindowsFormsHost() { Child = _myControl};
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多