简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM