温馨提示×

c#Winform自定义控件-导航菜单

c#
小云
137
2023-10-12 08:13:43
栏目: 编程语言

在C# Winform中自定义导航菜单的控件可以通过继承自Panel控件来实现。以下是一个简单的示例:

首先,创建一个名为NavigationMenu的自定义控件类,继承自Panel控件:

public class NavigationMenu : Panel
{
public NavigationMenu()
{
// 设置控件样式为双缓冲,以提高绘制效果
DoubleBuffered = true;
}
protected override void OnPaint(PaintEventArgs e)
{
// 绘制背景颜色
e.Graphics.FillRectangle(Brushes.LightGray, ClientRectangle);
// 绘制菜单项
int menuItemHeight = 30;
int menuItemWidth = Width;
int y = 0;
foreach (Control control in Controls)
{
control.Location = new Point(0, y);
control.Size = new Size(menuItemWidth, menuItemHeight);
y += menuItemHeight;
}
base.OnPaint(e);
}
}

然后,可以在窗体中使用该自定义控件来创建导航菜单。例如:

public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
NavigationMenu navigationMenu = new NavigationMenu();
navigationMenu.Dock = DockStyle.Left;
navigationMenu.Width = 200;
navigationMenu.BackColor = Color.DarkGray;
// 添加菜单项
Button homeButton = new Button();
homeButton.Text = "Home";
navigationMenu.Controls.Add(homeButton);
Button aboutButton = new Button();
aboutButton.Text = "About";
navigationMenu.Controls.Add(aboutButton);
// 添加自定义控件到窗体
Controls.Add(navigationMenu);
}
}

以上示例中,创建了一个继承自Panel控件的NavigationMenu类,并重写了OnPaint方法来自定义绘制。在窗体的构造函数中,创建了一个NavigationMenu实例,并添加了两个菜单项(Button控件)。然后将该自定义控件添加到窗体中。

运行程序,就可以看到自定义的导航菜单控件在窗体的左侧显示,并且菜单项以按钮的形式展示。

0