protected override Size MeasureOverride(Size availableSize)
{
if (this.RichTextContent == null) return new Size(0, 0);
// Make sure the RichTextBlock is a child, using the lack of
// a list of additional columns as a sign that this hasn't been
// done yet
if (this._overflowColumns == null)
{
Children.Add(this.RichTextContent);
this._overflowColumns = new List<RichTextBlockOverflow>();
}
// Start by measuring the original RichTextBlock content
this.RichTextContent.Measure(availableSize);
var maxWidth = this.RichTextContent.DesiredSize.Width;
var maxHeight = this.RichTextContent.DesiredSize.Height;
var hasOverflow = this.RichTextContent.HasOverflowContent;
// Make sure there are enough overflow columns
int overflowIndex = 0;
while (hasOverflow && maxWidth < availableSize.Width && this.ColumnTemplate != null)
{
// Use existing overflow columns until we run out, then create
// more from the supplied template
RichTextBlockOverflow overflow;
if (this._overflowColumns.Count > overflowIndex)
{
overflow = this._overflowColumns[overflowIndex];
}
else
{
overflow = (RichTextBlockOverflow)this.ColumnTemplate.LoadContent();
this._overflowColumns.Add(overflow);
this.Children.Add(overflow);
if (overflowIndex == 0)
{
this.RichTextContent.OverflowContentTarget = overflow;
}
else
{
this._overflowColumns[overflowIndex - 1].OverflowContentTarget = overflow;
}
}
// Measure the new column and prepare to repeat as necessary
overflow.Measure(new Size(availableSize.Width - maxWidth, availableSize.Height));
maxWidth += overflow.DesiredSize.Width;
maxHeight = Math.Max(maxHeight, overflow.DesiredSize.Height);
hasOverflow = overflow.HasOverflowContent;
overflowIndex++;
}
// Disconnect extra columns from the overflow chain, remove them from our private list
// of columns, and remove them as children
if (this._overflowColumns.Count > overflowIndex)
{
if (overflowIndex == 0)
{
this.RichTextContent.OverflowContentTarget = null;
}
else
{
this._overflowColumns[overflowIndex - 1].OverflowContentTarget = null;
}
while (this._overflowColumns.Count > overflowIndex)
{
this._overflowColumns.RemoveAt(overflowIndex);
this.Children.RemoveAt(overflowIndex + 1);
}
}
// Report final determined size
return new Size(maxWidth, maxHeight);
}