Opet jsem nad tim stravil par hodin ruznym zkousenim a tak bych se s vami chtel podelit o zpusob, ktery mi funguje. Jako vzdy je to tak jednoduche kdyz uz clovek vi jak na to, praktictejsi ale urcite vice nez tyto moje slova bude tech par radku kodu:
Prvne musime vytvorit bunku:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class DataGridViewFavoriteCell : DataGridViewImageCell { public DataGridViewFavoriteCell() { //-Nastavim vychozi typ, ktery bude vracet metoda GetFormattedValue ValueType = typeof(Bitmap); } protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, System.ComponentModel.TypeConverter valueTypeConverter, System.ComponentModel.TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context) { //-Vratim vychozi obrazek, ktery mohu pouzivat v metode Paint return Bitmaps.ci.FavoritePng; } protected override void Paint(System.Drawing.Graphics graphics, System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds, int rowIndex, DataGridViewElementStates elementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { Image imgFavorites = null; Point locFavorites = Point.Empty; //-Moje vlastni metoda na vypocet souradnic na ktere zakreslit, vypocet velikosti obrazku a take zmenseni obrazku na pozadovanou velikost. Je vhodne nastavit nemennost sirky a vysky radku pokud je radku hodne, obrazek nacist jen jednou a pak jen pocitat jeho souradnice Listing.CalculatePoint(cellBounds, Bitmaps.ci.FavoritePng, ImageFormats.Png, out locFavorites, out imgFavorites); //-Vymaluji samotny obrazek. Je nutno nejdrive vymalovat pozadi, protoze jinak se pouzije to co ma aplikace pod nim graphics.FillRectangle(Brushes.White, cellBounds); graphics.DrawImage(imgFavorites, locFavorites); Debug.Print(locFavorites.ToString()); //-Vymaluji okraje radku base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts); } } |
Pote sloupec:
1 2 3 4 5 6 7 8 9 |
class DataGridViewFavoriteColumn : DataGridViewImageColumn { public DataGridViewFavoriteColumn() { this.CellTemplate = new DataGridViewFavoriteCell(); this.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; this.ValueType = typeof(Bitmap); } } |
Ktery nakonec dame do DataGridView:
1 2 3 4 |
dataGridView1.Columns.RemoveAt(0); //-Timto zpusobem jsem se to taky pokousel delat jak s true, tak i false ale nepochodil jsem //dataGridView1.Columns.Insert(0, new DataGridViewImageColumn(true)); dataGridView1.Columns.Insert(0, new DataGridViewFavoriteColumn()); |
Takze konecny vysledek je treba takovy, s tim ze si v dalsich udalostech(treba OnCellClick) pretypovat na typ vasi vlastni bunky, nastavit treba priznak opacny a vyvolat prekresleni. Mate tak interaktivni bunku s obrazkem: