C# 制作自定义控件ComboBoxTreeView树形下拉框
程序员文章站
2022-06-09 08:01:04
...
效果图
创作思路
想要实现树形下拉框,又不想引用第三方UI控件,只要自己制作,在网上查了好做资料,加上本人的调整,决定使用ToolStripControlHost设计出下面的控件(搬砖(-^▽^-))
- 新建用户控件
- 实例化ToolStripControlHost、ToolStripDropDown、TreeView等
- 在构造函数中初始化
上代码
```csharp
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SkyMap.Common.UserControls
{
//需要继承ComboBox
public class ComboBoxTreeView : ComboBox
{
//windows消息中的鼠标点击和鼠标按下事件
private const int WM_LBUTTONDOWN = 0x201, WM_LBUTTONDBLCLK = 0x203;
//承载自定义控件或 Windows 窗体控件。
ToolStripControlHost treeViewHost;
//Menu类似menu的容器
ToolStripDropDown dropDown;
/// <summary>
/// 构造函数(默认是空的树)
/// </summary>
public ComboBoxTreeView()
{
TreeView treeView = new TreeView();
initTreeView(treeView);
}
/// <summary>
/// 初始化树下拉框
/// </summary>
/// <param name="internalTreeView">TreeView</param>
public void initTreeView(TreeView internalTreeView)
{
if (null!= internalTreeView)
{
internalTreeView.AfterSelect += new TreeViewEventHandler(treeView_AfterSelect);
internalTreeView.BorderStyle = BorderStyle.None;
internalTreeView.HideSelection = false;
treeViewHost = new ToolStripControlHost(internalTreeView);
dropDown = new ToolStripDropDown();
dropDown.Width = this.Width;
dropDown.Items.Clear();
dropDown.Items.Add(treeViewHost);
}
}
/// <summary>
/// 树控件选中事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void treeView_AfterSelect(object sender, TreeViewEventArgs e)
{
this.Items.Clear();
this.Items.Add(TreeView.SelectedNode.FullPath);
this.Text = TreeView.SelectedNode.Text;
this.Name = TreeView.SelectedNode.Name;
this.Tag = TreeView.SelectedNode.Tag;
this.Focus();
dropDown.Close();
}
/// <summary>
/// 设置选中的node
/// </summary>
/// <param name="node"></param>
public void SetCurSelected(TreeNode node)
{
this.TreeView.SelectedNode = node;
this.Items.Clear();
this.Items.Add(TreeView.SelectedNode.FullPath);
this.SelectedIndex = 0;
this.Name = TreeView.SelectedNode.Name;
this.Tag = TreeView.SelectedNode.Tag;
}
/// <summary>
/// 获取控件内的TreeView
/// </summary>
public TreeView TreeView
{
get { return treeViewHost.Control as TreeView; }
}
private void ShowDropDown()
{
if (dropDown != null)
{
treeViewHost.Size = new Size(DropDownWidth - 2, DropDownHeight);
dropDown.Show(this, 0, this.Height);
}
}
/// <summary>
/// 处理windows消息(此处是指点击combbox时弹出下拉框)
/// </summary>
/// <param name="m"></param>
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_LBUTTONDBLCLK || m.Msg == WM_LBUTTONDOWN)
{
ShowDropDown();
return;
}
base.WndProc(ref m);
}
/// <summary>
/// 释放内存
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (dropDown != null)
{
dropDown.Dispose();
dropDown = null;
}
}
base.Dispose(disposing);
}
}
}