星期二, 12月 29, 2020

[C#] TreeView 圖示

根據 
的筆記

把 ImageList 所需三張圖片,放在 Resource 內來使用


using System;
using System.Drawing;
using System.Windows.Forms;
using TreeViewImage.Properties;

namespace TreeViewImage
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        ImageList imageList4TreeView = new ImageList();

        private void Form1_Load(object sender, EventArgs e)
        {
            myTreeView.Font = new Font("微軟正黑體", 16F);

            // 建立搭配 TreeView 使用的 ImageList 圖庫
            imageList4TreeView.ImageSize = new Size(36, 36);
            imageList4TreeView.Images.Add(Resources.Community);
            imageList4TreeView.Images.Add(Resources.Man);
            imageList4TreeView.Images.Add(Resources.Woman);

            // 設定 TreeView 使用 ImageList
            myTreeView.ImageList = imageList4TreeView;

            DrawTreeView();
        }

        /// <summary>
        /// 在 TreeNode 內指定 ImageIndex 和 SelectedImageIndex 來顯示圖片
        /// </summary>
        private void DrawTreeView()
        {
            TreeNode root = new TreeNode() { Text = "組織圖" , ImageIndex = 0 };
            myTreeView.Nodes.Add(root);

            TreeNode DepartmentNode;
            TreeNode EmployeeNode;
            int index;
            for (int i = 1; i <= 2; i++)
            {
                DepartmentNode = new TreeNode() { Text = $"部門-{i}", ImageIndex = 0 , SelectedImageIndex = 0};
                root.Nodes.Add(DepartmentNode);

                for (int j = 1; j <= 4; j++)
                {
                    index = j % 2 == 0 ? 1 : 2;
                    EmployeeNode = new TreeNode() { Text = $"員工-{j}", ImageIndex = index , SelectedImageIndex = index };
                    DepartmentNode.Nodes.Add(EmployeeNode);
                }
            }

            myTreeView.ExpandAll();
        }
    }
}


SelectedImageIndex 說明
Gets or sets the image list index value of the image that is displayed when the tree node is in the selected state.
因為刻意變化每個 TreeNode 圖示,導致點選 TreeNode 後會根據 TreeView.SelectedImageIndex 來變化圖示,原是想說把 TreeView.SelectedImageIndex = -1 來取消,但沒有作用,最後是在建立 TreeNode 時會一併設定 TreeNode.SelectedImageIndex,避免受 TreeView.SelectedImageIndex 影響

ImageKey 和 ImageIndex 說明
ImageKey 和 ImageIndex 屬性互斥
  • 設定 ImageKey,ImageIndex 會自動設為 -1
  • 設定 ImageIndex,ImageKey 會自動設為空字串 ( "" ) 

沒有留言:

張貼留言