效果图:
wpf control + form = custom control.
+
=
设计与实现:
1. 按照上面的效果图,分别设计一个WPF控件和一个Windows Form窗口;这一步很简单,下面两步很重要!
2. 在frmHost.Designer.cs文件中添加如下代码:
private System.Windows.Forms.Integration.ElementHost m_elementHost; // 元素宿主
private ctlEmbed m_ctlEmbed; // wpf控件
3. 在frmHost.cs文件中添加如下代码:
private void frmHost_Load(object sender, EventArgs e)
{
m_elementHost = new System.Windows.Forms.Integration.ElementHost();
m_ctlEmbed = new ctlEmbed();
// m_elementHost
m_elementHost.Location = new Point(0, 0);
m_elementHost.Dock = DockStyle.Fill;
m_elementHost.Name = "elementHost";
m_elementHost.TabIndex = 0;
m_elementHost.Child = m_ctlEmbed;
// m_ctlEmbed
Controls.Add(m_elementHost);
}
4. 至此,一个简单的自定义控件就实现了! 欢迎大家一起交流,指正!