Pixel-length measuring code, like this one:
public int TextWidth(string text)
{
TextBlock t = new TextBlock();
t.Text = text;
t.Measure(new Size(1000, 1000));
return (int)t.DesiredSize.Width;
}
Is not working (result is 0) because it requires TextBlock to be displayed (visibility is not required), so it would require contact with gui thread, which is bad. It is already very ugly code, and any further bloating will make me vomit at sole thought of using it.
Graphics.MeasureString() is not available on WP platform.
So... is there any humanitarian way to do it? Solution is not required to be backward compatible with WP7, it even might be C++ code as it is in Runtime Component where I need text length, so ti would even shave off some native-managed-native computing time gobbling jumps.
Or maybe in the end I am making wrong approach?
I have TextBlock rendered on WriteableBitmap which is required to take on minimal size that can still fit whole text. Even with known max size that bitmap can take (screen resolution or parent size) it will still take up, depending on device screen, from 1MB to 7MB just for one bitmap at worst case. Which with predicted ~30 texts used in same time will be memory murdering. So this approach is even uglier in the end.
(Rendered is currently pathetic Image bobmarded with WriteableBitmaps in XAML app with logic placed in Runtime Component, in the end I plan to replace rendering module with DirectX, but for now it needs to just work with some acceptable speed and focus on important part in, app logic, as deadline for first version is closing in)
Try this:
Solution working on WP8 device (tested on HTC 8S and Lumia 920)
According to all information I found, ActualWidth should not be set until control is measured and arranged, but somehow it works while DesiredSize returned 0's for controls both measured and arranged, even ones statically added to form. Which is not as described in available materials.
This solution is still rather ugly one and, if I understood correctly, will fail to give correct number if device dpi is other than 96 as ActualWidht/Height value is in "device-independent unit" of 1/96. But for now, if I am not mistaken, all WP8 devices work in ye old 96dpi so until real solution will be found or made available (like desktop .NET Graphics.MeasureString()) it can act as surrogate.
MSDN about ActualWidth.