using System.Windows;
using System.Windows.Controls;
using System.Windows.Shapes;
namespace Oliver.Controls
{
public class RectangleArea : UserControl
{
#region Dependency properties
public static readonly DependencyProperty GapProperty =
DependencyProperty.Register(
"Gap",
typeof(double),
typeof(RectangleArea),
new PropertyMetadata(5d, OnValueChanged));
public double Gap
{
get { return (double)GetValue(GapProperty); }
set { SetValue(GapProperty, value); }
}
public static readonly DependencyProperty RectWidthProperty =
DependencyProperty.Register(
"RectWidth",
typeof(double),
typeof(RectangleArea),
new PropertyMetadata(5d, OnValueChanged));
public double RectWidth
{
get { return (double)GetValue(RectWidthProperty); }
set { SetValue(RectWidthProperty, value); }
}
public static readonly DependencyProperty RectHeightProperty =
DependencyProperty.Register(
"RectHeight",
typeof(double),
typeof(RectangleArea),
new PropertyMetadata(5d, OnValueChanged));
public double RectHeight
{
get { return (double)GetValue(RectHeightProperty); }
set { SetValue(RectHeightProperty, value); }
}
#endregion
#region Internal
private static void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
RectangleArea panel = (RectangleArea)sender;
panel.UpdateLayout();
}
protected override Size MeasureOverride(Size availableSize)
{
DrawContent(availableSize.Width, availableSize.Height);
return base.MeasureOverride(availableSize);
}
private void DrawContent(double width, double height)
{
Canvas canvas = new Canvas();
canvas.Background = this.Background;
RectWidth = RectWidth == 0 ? 1 : RectWidth;
RectHeight = RectHeight == 0 ? 1 : RectHeight;
double xd = width / (RectWidth + Gap);
double yd = height / (RectHeight + Gap);
for (int x = 0; x < xd; x++)
{
bool alternatingX = x % 2 == 0;
for (int y = 0; y < yd; y++)
{
bool alternatingY = y % 2 == 0;
Rectangle r = new Rectangle();
if ((alternatingX & !alternatingY) ||
(!alternatingX & alternatingY))
{
continue;
}
double left = x * (RectWidth + Gap);
double top = y * (RectHeight + Gap);
r.SetValue(Canvas.LeftProperty, left);
r.SetValue(Canvas.TopProperty, top);
r.Width = RectWidth;
r.Height = RectHeight;
r.Fill = this.Foreground;
canvas.Children.Add(r);
}
}
this.Content = canvas;
}
#endregion
}
}