[C#.NET][Winform] 具有圖形選項的 ListBox

  • 11416
  • 0
  • 2013-08-16

[C#.NET][Winform] 具有圖形選項的 ListBox

上篇有寫到一樣的東西 [Winform] 具有圖形選項的 ComboBox,本篇將用ListBox以及HatchStyle來處理,做不一樣的效果,不過程式碼的處理都是一樣的啦XD,本篇順便再解決上篇的一個小Bug,上篇因為少了DrawItemEventArgs.DrawBackground方法DrawItemEventArgs.DrawFocusRectangle方法,這兩個方法主要功能是

DrawBackground:出現光條

DrawFocusRectangle:在光條週邊產生虛線小框框

重點是DrawBackground要擺對地方,若是亂擺,就不會出現光條

image

 

改善過後,鼠標滑過去就會有藍色光條出現惹

image

 


接下來來實作本篇的重點:

首先:利用反射將HatchStyle加入到ListBox,別忘了設定ListBox.DrawMod屬性為OwnerDraw系列

private void Form1_Load(object sender, EventArgs e)
{
    this.listBox1.DrawMode = DrawMode.OwnerDrawFixed;
    //反射加入HatchStyle
    foreach (HatchStyle MyStyle in HatchStyle.GetValues(typeof(HatchStyle)))
    {
        this.listBox1.Items.Add(MyStyle);
    }
}

 

 

 

再來:利用ListBox.DrawItem事件重繪其內容

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    if (e.Index == -1)
        return;
    e.DrawBackground();//光條
    ListBox listBox = (ListBox)sender;
    //取出樣式
    HatchStyle style = (HatchStyle)listBox.Items[e.Index];
    Graphics graphics = e.Graphics;
    //畫出預覽框,用黑色
    Rectangle rect = e.Bounds;
    rect.Offset(1, 1);
    rect.Width = 50;
    rect.Height = 11;
    graphics.DrawRectangle(new Pen(Color.Black), rect);

    //填滿框框
    HatchBrush brush = new HatchBrush(style, Color.Red, Color.White);
    rect.Offset(1, 1);
    rect.Width -= 1;
    rect.Height -= 1;
    graphics.FillRectangle(brush, rect);
    graphics.DrawString(style.ToString(), e.Font, new SolidBrush(Color.Black), rect.X + 60, rect.Y - 2);
    e.DrawFocusRectangle();//焦點
}

 

 

 

最後:用ListBox.SelectIndexChanged事件來取出被選擇的項目

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (sender == null)
        return;
    ListBox listBox = (ListBox)sender;
    HatchStyle style = (HatchStyle)listBox.SelectedItem;
    HatchBrush brush = new HatchBrush(style, Color.Red, Color.White);
    this.panel1.CreateGraphics().FillRectangle(brush, this.panel1.ClientRectangle);
}

 

按下F5的執行畫面

image


 

 

後記:ListBox_DrawItem.zip

經過了上篇本篇跟練習,相信有心練習的人應該都學會用DrawItem事件來處理圖型選單,相信透過這樣的練習能對爾後的專案有幫助。

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo