In the TextBlock
class, there is a property to set the TextTrimming
behaviour of the control, when the text exceeds the bounds of the control.
However, I can't seem to find a property that can inform my application if the TextBlock
has been trimmed or not.
The problem I have is that I have a fixed sized TextBlock
that can have text the exceeds the size. When this happens, I want to dynamically adjust the font size to fit the text into the block.
Any idea's how I can do this?
Pseudo Code
// Function added to TextBlock as SizeChanged event handler.
private void textBlock_SizeChanged(object sender, SizeChangedEventArgs e)
{
TextBlock textBlock = sender as TextBlock;
if(textBlock.IsTrimmed && textBlock.FontSize > 10) // NOTE: IsTrimmed Property does not exist.
{
textBlock.FontSize -= 10;
}
}
Then the UI thread will recursively shrink the text until it fits into the TextBlock
Here is a solution that works.
private void textBlock_SizeChanged(object sender, SizeChangedEventArgs e)
{
TextBlock tb = sender as TextBlock;
if (tb != null)
{
Grid parent = tb.Parent as Grid;
if(parent != null)
{
if(parent.ActualWidth < tb.ActualWidth)
{
tb.FontSize -= 10;
}
}
}
}
Though its not very efficient. If there was an algorithm that could be used to determine the font size, string length and pixel width, it could be improved.