[C# 윈폼 문법] C# Winform(윈폼) Listbox(리스트박스) Item 항목에 Color(색상) 넣기


안녕하세요.

 

오늘은 C# 윈폼에서 ListBox 컨트롤 Item들의 배경 색상을 넣는 방법에 대해서 알려드리고자 합니다.

 

보통은 다른 컨트롤들은 BackColor 속성이 있어서 해당 속성에 사용자가 원하는 색상을 넣어주면 됐지만..ListBox 컨트롤은 DrawItem 이벤트를 이용하여 그려줘야 합니다.


 

그래서 좀 많이 다르더라구요! 물론 이 포스팅을 보시고 나서부터는 모두 알게 되실거에요~~^^

 

그럼 바로 예제를 통하여 ListBox 컨트롤 Item에 색상을 넣어보도록 하겠습니다.

 

먼저 아래와 같이 빈 폼에 ListBox 컨트롤을 배치해 주시기 바랍니다.

 

리스트박스 컨트롤 배치



예제코드


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

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 ListBoxTest

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

            InitListBox();

        }

 

        public void InitListBox()

        {

            uiLB_Color.Items.Add("Red");

            uiLB_Color.Items.Add("Blue");

            uiLB_Color.Items.Add("Green");

            uiLB_Color.Items.Add("Black");

 

            //DrawItem 이벤트 선언

            this.uiLB_Color.DrawItem += uiLB_Color_DrawItem;

        }

 

        public void uiLB_Color_DrawItem(object sender, DrawItemEventArgs e)

        {

            //기존 DrawMode 디폴트 값은 Normal 인데 

               //이것을 OwnerDrawFixed 바꿔준다.

            uiLB_Color.DrawMode = DrawMode.OwnerDrawFixed;

 

            e.DrawBackground();

 

            Brush myBrush = Brushes.Black;

 

            switch(e.Index)

            {

                case 0:

                    myBrush = Brushes.Red;

                    break;

                case 1:

                    myBrush = Brushes.Blue;

                    break;

                case 2:

                    myBrush = Brushes.Green;

                    break;

                case 3:

                    myBrush = Brushes.Black;

                    break;

            }

 

            e.Graphics.DrawString(uiLB_Color.Items[e.Index].ToString(), e.Font, 

myBrush, e.Bounds, StringFormat.GenericDefault);

            e.DrawFocusRectangle();

        }

    }

}

 

Colored by Color Scripter

cs


실행 결과



위와 같이 리스트박스에 항목들의 텍스트 Color가 각각 다르게 적용된 모습을 확인하실 수 있습니다.^^


이제 위의 예제코드를 통하여 응용된 버전을 사용하시면 될거에요~~

 

감사합니다!^^


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY