一、概要
因為要在項目中要在ListView中實現下拉框選擇,用DataGrid的話,一個不美觀,二個綁定數據麻煩,參考網上一種做法,就是單擊ListView時,判斷單擊的區域,然后將Combox控件顯示單擊的區域,以模擬效果,很少寫winform,寫的不好,望大家不要笑話。
二、准備控件
先在容器中拖入一個ListView控件和Combox控件,然后設置Combox控件的Visible屬性為False,即隱藏Combox控件,如圖:
隨便填充點數據到ListView和Combox中,如下:
1 this.listView1.SmallImageList = imageList1; 2 this.comboBox2.Items.Add("蘋果"); 3 this.comboBox2.Items.Add("香蕉"); 4 this.comboBox2.Items.Add("橘子"); 5 this.comboBox2.Items.Add("葡萄"); 6 ListViewItem item; 7 item = new ListViewItem(1.ToString()); 8 item.SubItems.Add("蘋果"); 9 item.SubItems.Add("香蕉"); 10 listView1.Items.Add(item); 11 item = new ListViewItem(2.ToString()); 12 item.SubItems.Add("橘子"); 13 item.SubItems.Add("葡萄"); 14 listView1.Items.Add(item);
三、封裝ListViewCombox類
該類主要實現點擊后將Combox控件顯示到點擊的區域中,同時,將Combox的SelectedIndexChanged和Leave事件也實現在該類中,代碼如下:
1 public class ListViewCombox 2 { 3 ListView _listView; 4 ComboBox _combox; 5 int _showColumn = 0; 6 ListViewSubItem _selectedSubItem; 7 8 /// <summary> 9 /// 列表combox 10 /// </summary> 11 /// <param name="listView">listView控件</param> 12 /// <param name="combox">要呈現的combox控件</param> 13 /// <param name="showColumn">要在哪一列顯示combox(從0開始)</param> 14 public ListViewCombox(ListView listView, ComboBox combox, int showColumn) { 15 _listView = listView; 16 _combox = combox; 17 _showColumn = showColumn; 18 BindComboxEvent(); 19 } 20 21 /// <summary> 22 /// 定位combox 23 /// </summary> 24 /// <param name="x">點擊的x坐標</param> 25 /// <param name="y">點擊的y坐標</param> 26 public void Location(int x, int y) { 27 ListViewItem item = _listView.GetItemAt(x, y); 28 if (item != null) { 29 _selectedSubItem = item.GetSubItemAt(x, y); 30 if (_selectedSubItem != null) { 31 int clickColumn = item.SubItems.IndexOf(_selectedSubItem); 32 if (clickColumn == 0) { 33 _combox.Visible = false; 34 } 35 else if (clickColumn == _showColumn) { 36 int padding = 2; 37 Rectangle rect = _selectedSubItem.Bounds; 38 rect.X += _listView.Left + padding; 39 rect.Y += _listView.Top + padding; 40 rect.Width = _listView.Columns[clickColumn].Width + padding; 41 if (_combox != null) { 42 _combox.Bounds = rect; 43 _combox.Text = _selectedSubItem.Text; 44 _combox.Visible = true; 45 _combox.BringToFront(); 46 _combox.Focus(); 47 } 48 } 49 } 50 } 51 } 52 53 private void BindComboxEvent() { 54 if (_combox != null) { 55 _combox.SelectedIndexChanged += combox_SelectedIndexChanged; 56 _combox.Leave += combox_Leave; 57 } 58 } 59 60 private void combox_Leave(object sender, EventArgs e) { 61 if (_selectedSubItem != null) { 62 _selectedSubItem.Text = _combox.Text; 63 _combox.Visible = false; 64 } 65 } 66 67 private void combox_SelectedIndexChanged(object sender, EventArgs e) { 68 if (_selectedSubItem != null) { 69 _selectedSubItem.Text = _combox.Text; 70 _combox.Visible = false; 71 } 72 } 73 }
四、使用
在容器代碼中,先聲明一個ListViewCombox類的全局實例,並在構造函數中實例化,最后在ListView中MouseUp事件中實現定位,如圖:
五、效果
因為上一步實例化ListViewCombox類時我傳入的顯示列為1,所以在ListView控件中單擊第二列時就會產生下拉效果,如圖:
六、總結
很少寫winform,但我感覺代碼都是相通的,最主要的是理解你要實現什么,然后進行抽象和封裝,希望對大家能有所幫助,也請高手對我進行指導,謝謝!