[英]C# - ListBox / ListView to support both data binding and thumbnails
在C#Windows窗体应用程序中,我想要一个支持两个功能的列表控件:
有一个简单的解决方案吗? 最好不要使用其他可下载产品的试用版。 一个常用的NuGet包就可以了。
您可以通过从ListBox
派生它来创建自己的ThumbnailListBox
:
public class ThumbnailListBox : ListBox
{
public ThumbnailListBox()
{
DrawMode = DrawMode.OwnerDrawFixed;
ItemHeight = 32;
}
...
}
然后你必须覆盖OnDrawItem
并绘制你的东西。 请注意,您还必须绘制文本。
protected override void OnDrawItem(DrawItemEventArgs e)
{
e.DrawBackground();
if (e.Index >= 0 && e.Index < Items.Count) {
var item = (MyItemType)Items[e.Index];
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Near;
stringFormat.LineAlignment = StringAlignment.Center;
var textRect = e.Bounds;
textRect.X += 35;
textRect.Width -= 35;
using (var textBrush = new SolidBrush(e.ForeColor)) {
e.Graphics.DrawString(item.Text, Font, textBrush, textRect, stringFormat);
}
Image img = item.GetThumbnail();
if (img != null) {
e.Graphics.DrawImage(img, 1, 1);
}
}
e.DrawFocusRectangle();
}
在此示例中,我假设您正在使用对象绑定到MyItemType
类型的MyItemType
。
如果您有不同大小的缩略图,则可以将DrawMode
设置为DrawMode.OwnerDrawVariable
,然后覆盖OnMeasureItem
,您可以在其中为每个项目指定不同的高度。
protected override void OnMeasureItem(MeasureItemEventArgs e)
{
if (e.Index >= 0 && e.Index < Items.Count) {
var item = (MyItemType)Items[e.Index];
e.ItemHeight = Math.Max(15, item.GetThumbnailHeight());
}
}
这可以在Blend for VS中轻松完成。 在Blend中,单击ListBox的属性。 单击Items属性。 在“添加”按钮左侧弹出窗口的底部屏幕上,选择其他类型。 将图像输入到提供的搜索文本框中。 选择图像。 在图像选择源上并添加所需的图片。 也可以通过更改其Source属性在C#中添加图片。 我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.