I have a problem when creating dynamically generated columns in my ObjectListView with ImageGetterDelegate used to set the image displayed in that field.
When trying to do the following:
myOLVColumn.ImageGetter = delegate(Object x) { /*can't access myOLVColumn here*/ return getImage(x); };
I can't access the original Column object inside the delegate (which I need to determine which image to display):
Maybe the solution is using some event that I couldn't find yet instead of the delegate.
Does anybody knows if it is possible to access the column object inside the delegate or set the field image based on the column properties in any other dynamic way?
if so, how?
If it is not possible then it would be great if they changed:
public delegate object ImageGetterDelegate(object rowObject);
to
public delegate object ImageGetterDelegate(object rowObject, object sender);
I found the solution by my own!
I can create an object before the delegate definition and then use that object inside of the delegate with no problem! It will be saved as a pointer in the delegate definition.
foreach (DirectoryInfo dir in directoryList.GetDirectories())
{
BrightIdeasSoftware.OLVColumn myOLVColumn = new BrightIdeasSoftware.OLVColumn();
myOLVColumn.ImageGetter = delegate(Object x) {
/*I CAN access myOLVColumn here,
as far as I don't mess with that object in the other code,
and even if the for loop changes myOLVColumn, as far as it makes a new one and don't destroy it
the delegate will still have the pointer to the object the variable pointed to
during the generation of the delegate*/
return getImage(x, myOLVColumn);
};
//...
}
The garbage collector won't delete that myOLVColumn object because it is being pointed by the delegate object.
This trick doesn't work well with primitive types because any change to that var will affect all the delegates since they are not a pointer to an object, so make sure to use the warpers (Int32 instead of int, String instead of string and so on).
Anyway it's kind of tricky so maybe it would be good if the delegate definition is extended, providing of course that it doesn't mess up too much the inner workings of the ObjectListView library.