在Winforms中使用具有多个控件的WPF扩展器

时间:2014-09-29 15:33:14

标签: c# winforms wpf-controls

我的问题是我想使用WPF扩展器对象来托管一些winforms控件。我将要使用它的位置在我的应用程序的设置表单中。但是,我无法找到的是添加多个控件。

经过大量搜索我的问题的解决方案后,我发现这个简单的代码只添加一个控件到WPF扩展器对象(我需要添加多个控件):

private void Form1_Load(object sender, EventArgs e)
    {
        System.Windows.Controls.Expander expander = new System.Windows.Controls.Expander();
        expander.Header = "Sample";
        WPFHost = new ElementHost();
        WPFHost.Dock = DockStyle.Fill;

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

        expander.Content = host;
        WPFHost.Child = expander;
        this.Controls.Add(WPFHost);
    }

在此代码中,扩展器仅承载一个控件。

如何自定义它以托管多个控件? 请帮忙

1 个答案:

答案 0 :(得分:1)

使用System.Windows.Forms.Panel作为容器将有所帮助:

private void Form1_Load(object sender, EventArgs e)
{
    System.Windows.Controls.Expander expander = new System.Windows.Controls.Expander();
    System.Windows.Controls.Grid grid = new System.Windows.Controls.Grid();
    expander.Header = "Sample";
    ElementHost WPFHost = new ElementHost();
    WPFHost.Dock = DockStyle.Fill;

    Panel panel1 = new Panel();
    DateTimePicker dtPicker1 = new DateTimePicker();
    Label label1 = new Label();


    // Initialize the Label and TextBox controls.
    label1.Location = new System.Drawing.Point(16, 16);
    label1.Text = "Select a date:";
    label1.Size = new System.Drawing.Size(104, 16);
    dtPicker1.Location = new System.Drawing.Point(16, 32);
    dtPicker1.Text = "";
    dtPicker1.Size = new System.Drawing.Size(152, 20);

    // Add the Panel control to the form. 
    this.Controls.Add(panel1);
    // Add the Label and TextBox controls to the Panel.
    panel1.Controls.Add(label1);
    panel1.Controls.Add(dtPicker1);


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


    expander.Content = host;
    WPFHost.Child = expander;
    this.Controls.Add(WPFHost);

}