在Windows窗体中托管堆栈面板

时间:2015-01-13 14:04:59

标签: c# wpf winforms wpf-controls

我的Windows窗体应用程序中有一个普通面板,我想添加一个堆栈面板,里面有WPF。

堆叠面板应包含2个扩展器控件。

我正在使用元素主机在窗体中使用堆栈面板和扩展器控件。

我正在使用以下代码:

       ElementHost WPF_Container = new ElementHost();
        WPF_Container.AutoSize = true;

        ElementHost WPF_Container1 = new ElementHost();
        WPF_Container1 .AutoSize = true;

        ElementHost StackPanelHost = new ElementHost();

        Expander expander1 = new Expander();
        expander1.Header = "Pipes";

        Expander Expander2 = new Expander();
        Expander2.Header = "Mountings";

        uc1 uc1 = new uc1(); // Object Creation for User Control-1
        uc2 uc2 = new uc2();  // Object Creation for User Control-2

        StackPanel Stackpanel = new StackPanel();
        Stackpanel.Orientation = System.Windows.Controls.Orientation.Vertical;


        WindowsFormsHost host = new WindowsFormsHost();
        host.Child  = uc1 ;

        WindowsFormsHost host2 = new WindowsFormsHost();
        host2.Child = uc2;


        expander1.Content = host;
        Expander2.Content = host2;

        Stackpanel.Children.Add(expander1);
        Stackpanel.Children.Add(Expander2);


        // WPF_Container.Child = expander1;
        // WPF_Container1.Child = Expander2;
        StackPanelHost.Child = Stackpanel;

        panel1.Controls.Add(StackPanelHost); // Adding Stack Panel to my Winform Panel.

在表单加载事件期间使用上面的代码没有控件添加到我的Windows窗体面板。 如何实现功能

1 个答案:

答案 0 :(得分:0)

以下是您如何执行此操作的示例:

ElementHost host = new ElementHost();
StackPanel wpfPanel = new StackPanel();
host.Child = wpfPanel;
//panel1 is Windows Forms Panel
panel1.Controls.Add(host);

我建议您在WPF用户控件中创建所需的UI,然后将其添加到ElementHost。

更新:

ElementHost host = new ElementHost();
StackPanel wpfPanel = new StackPanel();
host.Child = wpfPanel;
//panel1 is Windows Forms Panel
panel1.Controls.Add(host);
var testButton = new System.Windows.Controls.Button(){Content = "test"};
wpfPanel.Children.Add(testButton);

请注意您使用正确的命名空间作为Windows窗体以及Button类