Getting the line count of a wrapped TextBlock in WPF

May 22, 2015, 12:28 am

OK, so TextBlock does have a LineCount property, the only problem is, it is a private Property. It seems like half the private and internal fields should be public or at least protected so the children can get at them.

Rant: Sometimes I shake my head at the decisions made by the original developers, then I remember WPF is awesome and these little implementation mistakes aren’t always a big deal. Still, if they would just open source WPF, we could submit such a fix in seconds.

Well, let’s get around this. Did you know that you can access private fields and properties using reflection? You can. Simply follow the steps in this post:

We can use reflection to get the LineCount value. In the article, they use a PrivateValueAccessor static class. However, for this purpose, I will simply take the needed method.

Here is a child class of TextBlock that gets LineCount. It also updates the LineCount on Loaded and on SizeChanged, as the LineCount is zero before the control is loaded. Once it is loaded a resize could change the line count.

Entries (RSS) and Comments (RSS).
WPFSharp.com is subsidiary of Rhyous.com.Copyright ® Rhyous.com
Linking to content on this site is allowed without permission and as many as ten lines of any article can be used along with such link.
Any other use of the content is allowed only by permission of Rhyous.com.