覆盖类/向 ListviewItem 添加属性 (vb.net)
我有一个列表视图,但我想向其中的列表视图项添加 3 个属性(例如其中之一是“图像”)。
我可以制作一个具有 3 个属性的自定义类并仅继承 ListViewItem,但现在我需要使用 MultiSelect,因此这意味着执行以下操作(在 For Each 循环中):
ListView1.SelectedItems.Item(i).Image
不起作用,因为它返回一个 ListViewItem 而不是我的 CustomClass。
我总是可以这样做:Ctype(ListView1.selectedItems(i), MyCustomClass).Image
但是一遍又一遍地使用它似乎是一种浪费/错误的方法?
I have a listview but I would like to add 3 properties (for example one of them is "image") to the listviewitems in it.
I was fine with making a custom class with the 3 properties and just inheriting ListViewItem but now I need to use MultiSelect, so it means doing things like(in For Each loops):
ListView1.SelectedItems.Item(i).Image
don't work because it returns a ListViewItem not my CustomClass.
I could always do :Ctype(ListView1.selectedItems(i), MyCustomClass).Image
But using that over and over again seems like a waste/wrong way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是它的工作原理。 ListView 可以存储任何类型的 ListItem,并且要获取派生转换的属性,您必须对其进行转换。你做得正确。
That is simply how it works. ListView can store any kind of ListItem and to get to the properties of your derived cast, you have to cast it. You are doing it correctly.
子类化
ListViewItem
只是为了向其附加自定义属性并不是一个特别好的主意。该类提供Tag property
专门用于此目的,您应该使用您自己的对象而不是子类化来填充它。它在语法方面可能不会产生很大的差异,但它是一个更好的设计。
It's not a particularly good idea to subclass
ListViewItem
just to attach custom attributes to it. The class provides aTag
property for specifically this purpose and you should populate that with your own object instead of subclassing. It might not make a big difference syntax-wise, but it's a better design.