2015-07-28 84 views
0

我想创建这个视图。但我不知道如何制作这种按钮,用C#可行吗?如果是这样,请帮助我。如何在C#中的列中创建切换按钮?

http://i.stack.imgur.com/AKJbH.jpg

+0

使用wpf或表单? –

+0

@Rasmus,With forms –

+0

现在的问题是:'Column'是什么意思?你的每个按钮都有一个bool,但它上面还有某种字符串,或者可能是两个数字?所以:你想在哪里存储这些数据?显示两个开/关位图并不困难,但您需要决定使用哪些控件。 – TaW

回答

1

对于ListView控件,你可以得到的东西,通过

  • 分裂看起来像你的图像数据到Text和各Item/Subitem
  • 所有者绘制ListView
  • Tags存储两个图像(包括净空)在两个Bitmaps
  • 编码的MouseDown事件带来的“按钮”住

enter image description here

这里是业主绘制的代码。

private void listView3_DrawItem(object sender, DrawListViewItemEventArgs e) 
{ 
    Rectangle textBounds = e.Bounds; textBounds.Height /= 2; 
    e.Graphics.DrawImage(e.Item.Text == "True" ? bmpOn : bmpOff, e.Bounds.Location); 
    TextRenderer.DrawText(e.Graphics, e.Item.Tag.ToString(), 
          Font, textBounds, Color.Black, TFFcenter); 
} 

private void listView3_DrawSubItem(object sender, DrawListViewSubItemEventArgs e) 
{ 
    Rectangle textBounds = e.Bounds; textBounds.Height /= 2; 
    e.Graphics.DrawImage(e.SubItem.Text == "True" ? bmpOn : bmpOff, e.Bounds.Location); 
    TextRenderer.DrawText(e.Graphics, e.SubItem.Tag.ToString(), 
          Font, textBounds, Color.Black, TFFcenter); 
} 


private void listView3_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e) 
{ 
    e.DrawDefault = true; 
} 

处理点击一个ListView的代码很简单,但并不明显:

private void listView3_MouseDown(object sender, MouseEventArgs e) 
{ 
    ListViewHitTestInfo HI = listView3.HitTest(e.Location); 
    if (HI.SubItem != null) HI.SubItem.Text = HI.SubItem.Text == "True" ? "False" : "True"; 
    else if (HI.Item != null) HI.Item.Text = HI.Item.Text == "True" ? "False" : "True"; 
} 

DrawText呼叫使用TextFormatFlags居中的上半部分的文字:

TextFormatFlags TFFcenter = 
       TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter; 

的绝招是在准备整个ListView

对于我的测试,我用这个程序:

ImageList il = new ImageList(); 
il.ImageSize = new Size(1, bmpOff.Height); 
listView3.SmallImageList = il; 
for (int c = 0; c < listView3.Columns.Count; c++) 
     listView3.Columns[c].Width = bmpOff.Width; 

for (int i = 0; i < listView3.Columns.Count; i++) 
{ 
    ListViewItem lvi = new ListViewItem((i % 2 == 0).ToString()); 
    for (int c = 0; c < 5; c++) 
    { 
     lvi.SubItems.Add(((c+i) % 2 == 0).ToString()); 
     lvi.SubItems[c].Tag = "3/7"; 
    } 
    lvi.Tag = "3/7"; 
    listView3.Items.Add(lvi); 

} 
listView3.Width = listView3.Columns.Count * bmpOff.Width + 4; 

注意我如何使用虚拟ImageList,而你在它执行Item heights..but,它可能是一个更好的主意来添加ImageList在设计和存储在其中的Bitmaps ..

当您要访问/更改上面你需要使用的各个Item/SubitemTag的按钮显示的文本..!

也可以使用DataGridView,并通过单元格绘画获得相同的外观。

请注意,没有任何解决方案适合数据绑定,因为您有太多数据无法绑定每个项目/单元格!

0

在Windows窗体中。 (它看起来像你正在使用的。)你可以在表单上放置一个DataGridView,并将GridView设计器中的ColumnType改为DataGridViewCheckBoxColumn。这会给你你正在寻找的功能。换句话说,如果你不介意外观,(但是需要相同的功能),你可以在网格中使用复选框。

当您具有正确的功能时:您可以使用Gnqz的上述答案来获取按钮的外观。