繁体   English   中英

C# - ListBox / ListView支持数据绑定和缩略图

[英]C# - ListBox / ListView to support both data binding and thumbnails

在C#Windows窗体应用程序中,我想要一个支持两个功能的列表控件:

  1. ListView样式的缩略图显示 ListView允许您将其绑定到ImageList,但ListBox不支持缩略图。
  2. 绑定数据 - ListBox允许您使用DataSource属性绑定“对象”列表。 但是我只需要能够将数据绑定到每个项目的标题和ID值,以便可以根据点击的任何项目进行适当的处​​理。 不幸的是,就我所知,ListView没有这样的功能。

有一个简单的解决方案吗? 最好不要使用其他可下载产品的试用版。 一个常用的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM