Search code examples
wpftextblockmeasurecontentpresenter

How to get the actual width and actual height for a control in WPF platform


I am preparing a custom control in the WPF platform in which I am using a content presenter for displaying a view and I am trying to display a text over the content presenter content using the text block control. For the given text in the text block, I tried to calculate the actual width and actual height for the text block using the measure method for positioning the text block control, but it doesn't provide the actual width and height for the text block control. So that the text block control is not displaying in the view. The code snippet is provided below: this.CustomTextBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

Can anyone suggest to me how to calculate the actual width and actual height for controls in the WPF platform and also explain to me why the measuring method is not providing the actual width and actual height for the control in the WPF platform?

I have also attached the project download link below:[https://www.syncfusion.com/downloads/support/directtrac/general/ze/BViewWpf1629602448][DemoProject]


Solution

  • UIElement.Measure is a method that is executed by the framework's layout engine.
    Measure is executed during the first layout pass and actually calculates the DesiredSize, which is used in the second layout pass when Arrange is invoked. Arrange may uses (depending on the implementation) DesiredSize to arrange its child elements. Measure has no direct influence on the actual size. It only calculates the maximum available space. The size passed into this method is not mandatory as it can be overridden by the measuring algorithm. The argument is considered to be minimum available space.

    If you want to modify the size of a FrameworkElement, set the Width and Height properties.

    To prevent the TextBlock from occupying the maximum available horizontal space, just set the HorizontalAlignment to something other than the default value HorizontalAlignment.Stretch:

    <!-- Use Padding to add additional space -->
    <TextBlock Text="Minimum sized TextBlock" 
               HorizontalAlignment="Left" />