Search code examples
c#wpfwidthrichtextboxflowdocument

Get automatically determined value of FlowDocument.PageWidth property


I have a WPF RichTextBox control, and I set the value of the RichTextBox.Document.PageWidth property to double.NaN in order to have the value be determined automatically.

Now I'd like to get the automatically determined value, but I cannot do so by reading the value of the property, as it returns double.NaN.

EDIT

I try getting the value of RichTextBox.DesiredSize in the OnMyPropertyChanged method of the property that can be set to auto (with a value of double.NaN):

if (!double.IsNaN(MyProperty)) richTextBox.Width = MyProperty;
else richTextBox.Width = richTextBox.DesiredWidth;

However, DesiredSize returns 0 on both axis.


Solution

  • Create a TextBlock control (without necessarily adding it to any parent control), set the text value you need to get the width of, and also the font properties (FontFamily, FontStyle, FontWeight, FontStretch and FontSize), then call the Measure method on the control, so that it determines the value of its DesiredSize property, which you can read then.