[이미지 1] 속성 변경

 

ListBox 개체의 DrawMode를 OwnerDrawFixed로 변경하고

ItemHeight를 변경합니다.

 

 

 

[이미지 2] DrawItem 이벤트 등록

 

사용자가 그리기로 속성을 변경하였으므로

Item을 직접 그려줘야합니다.

DrawItem 이벤트를 등록합니다.

 

이벤트 등록 하고

아래와 같이 구현하시면 완성된 ListBox를 확인하실수 있습니다.

 

 

        private void lb_propertyList_DrawItem(object sender, DrawItemEventArgs e)
        {
            e.DrawBackground();
            e.Graphics.DrawString(this.lb_propertyList.Items[e.Index].ToString(),
                e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
            e.DrawFocusRectangle();
        }


 

 

 

[이미지 3 ] 결과 화면

 

 

 

 

아래의 사항에 대해 더 적어보겠습니다.

 

1. Item 문자의 위치를 중간으로 위치

2. 아이템이 선택 되었을 때 폰트는 흰색

 

 

 

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

namespace Intelligent
{
    public partial class FormMapOptions : Form
    {
        /// <summary>
        /// ListBox 개체의 SelectedIndex 이전 값입니다.
        /// </summary>
        int prevLBSelectedIndex = -1;

        public FormMapOptions()
        {
            InitializeComponent();
            this.InitListBox();
        }

        private void InitListBox()
        {
            //ItemHeght는 아이템의 개수에 따라 달라집니다.
            this.lb_propertyList.ItemHeight = (this.lb_propertyList.Height / this.lb_propertyList.Items.Count);
            this.lb_propertyList.SelectedIndex = 0;
        }

        private void lb_propertyList_DrawItem(object sender, DrawItemEventArgs e)
        {
            e.DrawBackground();

            Brush brush;
            if (this.lb_propertyList.SelectedIndex == e.Index)
                brush = Brushes.White;
            else
                brush = Brushes.Black;

            //Font의 Height를 더한 만큼 좌표를 변경합니다.
            int x = e.Bounds.X + e.Font.Height;
            int y = e.Bounds.Y + e.Font.Height;

            e.Graphics.DrawString(this.lb_propertyList.Items[e.Index].ToString(),
                e.Font, brush, x, y, StringFormat.GenericDefault);
            e.DrawFocusRectangle();
        }
        
        private void lb_propertyList_SelectedIndexChanged(object sender, EventArgs e)
        {
            //맨처음을 제외하고 Item 선택이 변경되면
            //이전의 선택 되어있던 아이템의 문자 색상을 White->Black으로 변경 하기 위해
            //Invalidate 메서드를 호출해 아이템을 다시그립니다.
            if (this.prevLBSelectedIndex != -1)
                this.lb_propertyList.Invalidate(this.lb_propertyList.GetItemRectangle(this.prevLBSelectedIndex));

            this.prevLBSelectedIndex = this.lb_propertyList.SelectedIndex;
        }
    }
}


 

 

 

 

 

 

[이미지 4] 결과화면

'.Net > Winform' 카테고리의 다른 글

C# GDI+ Rectangle 영역 색상 반전  (0) 2012.12.28
C# 사용자별 개별 저장소 제공하기  (0) 2012.12.21
C# TabControl Tab Background 변경  (0) 2012.12.11
C# 디스플레이 정보 가져오기  (0) 2012.12.06
C# Color->Brush  (0) 2012.11.26

+ Recent posts