How to bind Windows Form Control to a “Grid” Panel using MVVM in WPF

﹥>﹥吖頭↗ 提交于 2021-01-28 11:20:57

问题


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.

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>

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:

XAML:

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

In my 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.


回答1:


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

XAML:

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

ViewModel:

    private System.Windows.Forms.Control _myControl;

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


来源:https://stackoverflow.com/questions/17625873/how-to-bind-windows-form-control-to-a-grid-panel-using-mvvm-in-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!