Asp tutorial. net winform listview Control
Using system. collections. generic;
Using system. drawing;
Using system. windows. forms;
Namespace qiqi. windows. forms
{
Public class qiqilistbox: control
{
Private readonly list <qiqilistboxitem> _ items;
Private color _ border_color;
Private int _ item_height;
Private color _ selected_back_color;
Private int _ selected_index;
Public qiqilistbox ()
{
Setstyle (controlstyles. userpaint | controlstyles. allpaintinginwmpaint, true );
_ Items = new list <qiqilistboxitem> ();
_ Item_height = 24;
_ Selected_index =-1;
_ Border_color = color. fromargb (245,170,114 );
_ Selected_back_color = color. fromargb (255,237,209 );
}
Public color bordercolor
{
Get {return _ border_color ;}
Set {_ border_color = value ;}
}
Public color selectedbackcolor
{
Get {return _ selected_back_color ;}
Set {_ selected_back_color = value ;}
}
Public int selectedindex
{
Get {return _ selected_index ;}
Set {_ selected_index = value ;}
}
Public int itemheight
{
Get {return _ item_height ;}
Set {_ item_height = value ;}
}
Public void insert_item (qiqilistboxitem, int index)
{
_ Items. insert (index, item );
}
Public void delete_item (int index)
{
_ Items. removeat (index );
}
Protected override void onpaintbackground (painteventargs pevent)
{
Base. onpaintbackground (pevent );
// Border
Using (var pen = new pen (_ border_color ))
{
Rectangle rect = displayrectangle;
Rect. width-= 1;
Rect. height-= 1;
Pevent. graphics. drawrectangle (pen, rect );
}
}
Protected override void onpaint (painteventargs e)
{
For (int I = 0; I <_ items. count; I ++)
{
Draw_item (e. graphics, I, I = _ selected_index );
}
}
Private void draw_item (graphics g, int index, bool selected)
{
Qiqilistboxitem item = _ items [index];
Rectangle rect = get_item_rect (index );
Using (brush bru = new solidbrush (selected? _ Selected_back_color: backcolor ))
{
G. fillrectangle (bru, rect );
}
// Icon
G. drawimage (item. image, 1, 1 + index * _ item_height, 24, 24 );
Rectangle rect_text = rect;
Rect_text.width-= 24;
Rect_text.x + = 24 + 10;
Var sf = new stringformat ();
Sf. linealignment = stringalignment. center;
G. drawstring (item. text, font, brushes. black, rect_text, sf );
}
Private rectangle get_item_rect (int index)
{
Return new rectangle (2, index * _ item_height + 2, width-4, _ item_height );
}
Public int hit_test (int x, int y)
{
For (int I = 0; I <_ items. count; I ++)
{
If (get_item_rect (I). contains (x, y ))
Return I;
}
Return-1;
}
Protected override void onmousedown (mouseeventargs e)
{
Base. onmousedown (e );
Int index = hit_test (e. x, e. y );
Graphics g = creategraphics ();
If (_ selected_index! =-1)
Draw_item (g, _ selected_index, false );
If (index! =-1)
{
_ Selected_index = index;
Draw_item (g, index, true );
}
}
}
Public class qiqilistboxitem
{
Public image {get; set ;}
Public string text {get; set ;}
Public object tag {get; set ;}
}
}