I want to make a user-drawn control for the only purpose of displaying a Color[,] array. The control itself should draw an NxM grid of rectangles of corresponding colors.
I'm trying to inherit from a FrameworkElement and to override OnRender method:
public class CustomControl1 : FrameworkElement
{
static CustomControl1()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
}
public Color[,] ColorCollection
{
get { return (Color[,])GetValue(ColorGridProperty); }
set { SetValue(ColorGridProperty, value); }
}
public static readonly DependencyProperty ColorGridProperty =
DependencyProperty.Register("ColorCollection", typeof(Color[,]), typeof(CustomControl1),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
protected override void OnRender(DrawingContext drawingContext)
{
if (ColorCollection != null)
{
int dimx = this.ColorCollection.GetLength(0);
int dimy = this.ColorCollection.GetLength(1);
double w = this.ActualWidth / dimx;
double h = this.ActualWidth / dimy;
for (int x = 0; x < dimx; x++)
{
for (int y = 0; y < dimy; y++)
{
SolidColorBrush brush = new SolidColorBrush(ColorCollection[x, y]);
drawingContext.DrawRectangle(brush, null, new Rect(x * w, 0, w, this.ActualHeight));
}
}
}
}
}
The problem is that my control doesn't redraw itself when i change elements in the underlying array. It works fine when i assign a whole new array or resize the control though.
Obviously I need another class which somehow notifies control about internal changes in the collection. I was looking at INotifyCollectionChange and ObservableCollection but the only articles I found were about binding collections to existing controls, not custom user-drawn ones. So I got confused and stuck at this point.