TreeView实现类似Outlook在收件箱后面显示新邮件数

本文介绍如何使用 C# 在 TreeView 控件中自定义显示新邮件数量的方法,通过 DrawNode 事件实现在节点后显示括号内的数字,如收件箱 (3)。文章提供完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Outlook、Foxmail 在收到新邮件后,在收件箱的后面会显示新邮件数:收件箱(1)。我们在做应用时有时也需要类似的功能,比如警示管理中显示警示信息的条数等。怎么实现呢?看了 TreeVeiw 和 TreeNode 属性和方法,没有发现可以直接实现的;在 Google 和百度上也没有搜索到。不过 TreeView 控件有一个 DrawNode 事件,通过该事件可以自己绘制节点,可以实现我们想要的这种功能:收件箱(1)。我想其他朋友可能也正在思考怎么实现这个功能呢,共享一下吧,免得大家再走弯路。

实现效果:


实现代码:
private void Form1_Load(object sender, EventArgs e)
{
    TreeNode root 
= new TreeNode("myname@163.com");
    root.Name 
= "root";
    root.Nodes.Add(
"InBox","收件箱");
    root.Nodes.Add(
"OutBox","发件箱");
    root.Nodes.Add(
"SentBox""已发送邮件箱");
    root.Nodes.Add(
"Spam""垃圾邮件箱");
    root.Nodes.Add(
"TrashBox""废件箱箱");
    
this.treeView1.Nodes.Add(root);
    
this.treeView1.ExpandAll();

    
// 设置绘制模式为 OwnerDrawText:
    
//    节点的标签部分手工绘制,其他部分系统绘制
    treeView1.DrawMode = TreeViewDrawMode.OwnerDrawText;
}

private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
    
// 由系统绘制
    e.DrawDefault = true;
    
// 在节点的后面绘制“新邮件数”。类似:收件箱(3)
    if (e.Node.Tag != null)
    {
        
string newMail = string.Format("({0})", e.Node.Tag.ToString());
        e.Graphics.DrawString(newMail, e.Node.TreeView.Font, Brushes.Blue, e.Bounds.Right, e.Bounds.Top);
    }
}

private void newMailButton_Click(object sender, EventArgs e)
{
    TreeNode inBoxNode 
= this.treeView1.Nodes["root"].Nodes["InBox"];
    inBoxNode.Tag 
= "3";
    
this.treeView1.Refresh();
}

private void readMailButton_Click(object sender, EventArgs e)
{
    TreeNode inBoxNode 
= this.treeView1.Nodes["root"].Nodes["InBox"];
    inBoxNode.Tag 
= null;
    
this.treeView1.Refresh();
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值