0

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.

IAbstract
  • 19,551
  • 15
  • 98
  • 146
Pavel Murygin
  • 2,242
  • 2
  • 18
  • 26

2 Answers2

0

You probably can create a custom collection for yourself that works like your 2D array, but you need to also implement INotifyCollectionChange interface, which is not so hard to implement. That way WPF will listen to your collection changes and update the control if necessary.

Hadi Eskandari
  • 25,575
  • 8
  • 51
  • 65
0

I think the sample may be useful.

Community
  • 1
  • 1