C# 卡片式导航

时间:2022-12-08 09:57:20

一 卡片式导航

界面导航,是指引导用户来使用程序的各个功能。
技术点分析:
① 左侧:功能菜单,使用ListBox实现;
② 右侧:一个容器,可以容纳多张卡片;

二 自定义ListBox

ListBox的自定义:
① DrawMode属性:OwnerDrawVariable;
② MeasureItem事件:负责计算每一想的高度;
③ DrawItem事件:负责每一项的绘制;

列表项的绘制DrawItem:
① 列表项索引 e.Index;
② 列表项矩形 e.Bounds;
③ 绘制工具 e.Graphics;
④ 列表项的状态e.State;
注意:应该根据列表项的状态,绘制不同的样式。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 自定义ListBox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            //自定义模式
            listBox1.DrawMode = DrawMode.OwnerDrawVariable;

            //
            listBox1.Items.Add("明细");
            listBox1.Items.Add("客户");
            listBox1.Items.Add("帮助");
            listBox1.SelectedIndex = 0;
        }
        //计算每一行的高度
        private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
        {
            e.ItemHeight = 50;
        }

        private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            int index = e.Index;
            if (index < 0) return;

            object item = listBox1.Items[index];
            string text = item.ToString();
            Rectangle rect = e.Bounds;
            Graphics g = e.Graphics;

            Color bgColor = Color.White;
            Color textColor = Color.FromArgb(44, 45, 45);

            if((e.State&DrawItemState.Selected)>0)
            {
                bgColor = Color.FromArgb(100, 240, 240, 240);
                textColor = Color.SkyBlue;
            }

            //背景
            using(Brush brush=new SolidBrush(bgColor))
            {
                g.FillRectangle(brush, rect);
            }

            //文字
            using(Brush brush=new SolidBrush(textColor))
            {
                StringFormat sf = new StringFormat();
                sf.Alignment = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;
                g.DrawString(text, listBox1.Font, brush, rect, sf);
            }
        }
    }
}

三 功能菜单

功能菜单:自定义ListBox,用于导航
① 每一项高度为50;
② 每一项FuncItem;
③ text文本;
④ icon图标;
⑤ cmd关联的命名;

自定义控件的三种方式:
① 组合
class X:UserControk{};
② 扩展
class X:ListBox{};
③ 自定义
class X:Control{};

在设计上,FuncMenu控件是可以重用的。符合“可读,可扩展,可重用”三大设计标准。

四 卡片容器

AfCardLayout:卡片容器,可以容纳多张卡片;
① AddCard(c,name)添加卡片;
② ShowCard(name)显示卡片;
每个卡片关联一个Name,用于显示卡片;

五 卡片容器的设计

AfCardLayout:本身就是一个Panel。
① 每一个子控件,就是一个卡片;
② 同一时间,只显示一个卡片;
③ 当前卡片占满整个空间;

总结

实现:
① 添加FuncMenu,于左侧;
② 添加AfCardLayout,于*;
③ 添加一个文件夹,添加几个卡片;
MyClientCard,MyDetailCard,MyHelpCard;
修改Form1 初始化;
给FuncMenu添加事件处理,切换界面;

功能集成.rar: https://url09.ctfile.com/f/22158009-741480556-5a5dcd?p=5939 (访问密码: 5939)