How to create a comparable Image
I have a DataGridView which has been bound to a generic BindingList. I want to be able to apply sort and search on columns of type DataGridViewImageColumn. The basic idea is to store a name into the image Tag and use is for sorting and searching. How can I do that?
It seems several ways to do it:
- Creating a new class inheriting
System.Drawing.Imageand making it comparable.Imageis an abstract class and if I inherit from it (as well asIComparableinterface), I'll encounter with this error message: The type 'System.Drawing.Image' has no constructors defined. What's the problem here? Image is anabstractnot asealedclass, but it doesn't allow me to inherit it!
Using protected override
ApplySortCoremethod of inherited class fromBindingList<T>.This method is like so:
class MyBindingList<T> : BindingList<T> { ... protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction) { if (prop.PropertyType.Equals(typeof(Image))) { /* I have no idea! */ } } }
- Creating a new
DataGridViewColumninheriting fromDataGridViewImageColumn.- This doesn't seem to be easy and may be used if other ideas are unusable.
Thanks 开发者_Go百科in advance
Create a class (X) that incapsulates System.Drawing. Image + ImageAlias string property. Bind your image column to X.Image and search over X.ImageAlias.
Sorry but don't have a coding tool on my hands to provide an example, but this is a basic idea.
Hope this helps.
I found the way!
MyBindingList
class MyBindingList<T> : BindingList<T>
{
...
protected override void ApplySortCore(PropertyDescriptor prop,
ListSortDirection direction)
{
if (prop.PropertyType.Equals(typeof(Image)))
{
_SortPropertyCore = prop;
_SortDirectionCore = direction;
var items = this.Items;
Func<T, object> func =
new Func<T, object>(t => (prop.GetValue(t) as Image).Tag);
switch (direction)
{
case ListSortDirection.Ascending:
items = items.OrderBy(func).ToList();
break;
case ListSortDirection.Descending:
items = items.OrderByDescending(func).ToList();
break;
}
ResetItems(items as List<T>);
ResetBindings();
}
else
{
...
}
}
private void ResetItems(List<T> items)
{
base.ClearItems();
for (int itemIndex = 0; itemIndex < items.Count; itemIndex++)
{
base.InsertItem(itemIndex, items[itemIndex]);
}
}
}
MyDataObject
class MyDataObject : INotifyPropertyChanged
{
...
public Image MyProp
{
get
{
return CreateComparableImage(myImage, "myImage");
}
}
private Image CreateComparableImage(Image image, string alias)
{
Image taggedImage = new Bitmap(image);
taggedImage.Tag = alias;
return taggedImage;
}
}
Form
class MyForm : Form
{
...
void BindDGV()
{
dataGridView1.Columns["myColumnName"].DataPropertyName = "MyProp";
dataGridView1.DataSource = MyBindingList<MyDataObject>(...);
}
}
加载中,请稍侯......
精彩评论