Reputation: 13334
I currently have a need for a custom ListViewItem
class - let's call it MyListViewItem
. It needs to have some additional data associated with each item, and perform some operations when the Checked property is changed. I've tried several things, but currently the relevant code looks like this:
class MyListViewItem : ListViewItem {
new public bool Checked {
get {
return base.Checked;
}
set {
base.Checked = value;
// do some other things here based on value
}
}
public MyListViewItem(Object otherData) {
// ...
}
}
The problem I'm having is that when I click on the item's checkbox in the ListView, my setter is never called. Does anyone know what I am doing wrong? I'm aware that I could use the ItemChecked event of the parent ListView, but that seems like a much less clean solution. (Also I'm not actually passing an Object to the constructor, but that part isn't important here).
Upvotes: 13
Views: 39649
Reputation: 5981
Instead of creating your own custom ListViewItem, why not create a seperate type to contain your custom data and then assign each ListViewItem Tag property with a reference to the custom data?
This is the pattern that I've been using for some time and it works very well. As for custom action when items are checked, simply handle the relevant events in the list view.
Upvotes: 1
Reputation: 4339
The ListViewItem.Checked property is not virtual (see MSDN doc here) so you will not be able to override the behavior of it in this way. You will have to use the event or derive from ListView and override ListView.OnItemChecked to change the behavior.
Upvotes: 1
Reputation: 25409
It's not working cause the "new" keyword doesn't override it just "hides".
This means that if you call Checked on an instance of object that is referenced through the type definition of MyListViewItem you will run your code. However the ListView references to this object via the type definition of ListViewItem and therefore will not call your "new" method.
"new" is not override. The better solution is to probably handle the code in a custom list view. It isn't really that ugly.
Upvotes: 18
Reputation: 161773
Assuming that the ListViewItem
.Checked
property is virtual, you need to override it:
public override bool Checked
Upvotes: 3
Reputation: 421988
new
does not override
the base
member. It declares a new method with the same name. In VB.NET it's called Shadows
.
Indeed, new
doesn't do anything except turning off a compiler warning. The member you do not declare as override
(and you can only do this if the base
member is virtual
or override
) will be completely unrelated to the inheritance tree of the base
member.
Upvotes: 9