如何将 Windows 窗体控件绑定到“网格"在 WPF 中使用 MVVM 的面板 [英] How to bind Windows Form Control to a "Grid" Panel using MVVM in WPF

查看:30
本文介绍了如何将 Windows 窗体控件绑定到“网格"在 WPF 中使用 MVVM 的面板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am attempting to use MVVM to Bind a Windows Form Control to a panel in 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.

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

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:

<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 中执行以下操作:

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:

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

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

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.

推荐答案

多加挖掘,原来我真的想把它绑定到一个ContentControl"标签上,如下:

Doing more digging, it turns out that I really wanted to bind this to a "ContentControl" tag, as follows:

XAML:

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

视图模型:

    private System.Windows.Forms.Control _myControl;

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

这篇关于如何将 Windows 窗体控件绑定到“网格"在 WPF 中使用 MVVM 的面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆