以下是完整的解决方案,即指定或不指定uniformgrid的列和行的句柄:
public class CartesianGrid : UniformGrid
{
private int _columns;
private int _rows;
private int _margin = 20;
public CartesianGrid()
{
// add some margin so the letters and numbers do show up
this.Margin = new Thickness(_margin, _margin, 0, 0);
}
protected override void OnRender(DrawingContext dc)
{
double xOffset = (this.RenderSize.Width / _columns);
double yOffset = (this.RenderSize.Height / _rows);
double xCenterOffset = xOffset / 2;
double yCenterOffset = yOffset / 2.3;
for (int i = 0; i < _columns; i++)
{
dc.DrawText(
new FormattedText((i + 1).ToString(),
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface("Arial"),
20,
Brushes.Black), new Point((i * xOffset) + xCenterOffset, _margin * -1));
}
for (int i = 0; i < _rows; i++)
{
dc.DrawText(
new FormattedText(((char)(i + 65)).ToString(),
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface("Arial"),
20,
Brushes.Black), new Point(_margin * -1, (i * yOffset) + yCenterOffset));
}
base.OnRender(dc);
}
protected override Size ArrangeOverride(Size arrangeSize)
{
if (this.Columns != 0 && this.Rows != 0)
{
_rows = this.Rows;
_columns = this.Columns;
return base.ArrangeOverride(arrangeSize);
}
else
{
Size arrangedSize = base.ArrangeOverride(arrangeSize);
double maxChildDesiredWidth = 0.0;
double maxChildDesiredHeight = 0.0;
// Measure each child, keeping track of max desired width & height.
for (int i = 0, count = Children.Count; i < count; ++i)
{
UIElement child = Children[i];
Size childDesiredSize = child.DesiredSize;
if (maxChildDesiredWidth < childDesiredSize.Width)
{
maxChildDesiredWidth = childDesiredSize.Width;
}
if (maxChildDesiredHeight < childDesiredSize.Height)
{
maxChildDesiredHeight = childDesiredSize.Height;
}
}
if (maxChildDesiredHeight == 0 || maxChildDesiredWidth == 0)
return arrangedSize;
_columns = Convert.ToInt32(Math.Floor(this.DesiredSize.Width / maxChildDesiredWidth));
_rows = Convert.ToInt32(Math.Floor(this.DesiredSize.Height / maxChildDesiredHeight));
return arrangedSize;
}
}
}
顺便说一句,这就是我想要实现的目标:
http://wpfdude.blogspot.com/2010/06/cartesian-grid.html
谢谢!