'Why is UIElement.DesiredSize different when UIElement.Parent is null and not null

Why is UIElement.DesiredSize different when UIElement.Parent is null and not null

I need to calculate the dimensions of elements that are not on the form. I am using code

       Element = new Element()
       Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
       Size result = Element.DesiredSize;

But I get different results when Element.Parent = null and when Element.Parent != null

Properties UseLayoutRounding, SnapsToDevicePixels don't help

Here is a complete example

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        TextBlock cell1 = CreateTextBlock();
        cell1.InvalidateMeasure();
        //VisualTreeHelperEh.ForAllChildren(cell1, true, true, (lmt) => lmt.InvalidateMeasure());
        cell1.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
        Size result1 = cell1.DesiredSize;
        double height1 = cell1.DesiredSize.Height;
        Debug.WriteLine("height1=" + height1.ToString());
    
        TextBlock cell2 = CreateTextBlock();
        cell2.UseLayoutRounding = true;
        cell2.SnapsToDevicePixels = true;
        //VisualTreeHelperEh.ForAllChildren(cell2, true, true, (lmt) => lmt.InvalidateMeasure());
        cell2.InvalidateMeasure();
        cell2.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
        Size result2 = cell2.DesiredSize;
        double height2 = cell2.DesiredSize.Height;
        Debug.WriteLine("height2=" + height2.ToString());
    
        TextBlock cell3 = CreateTextBlock(); 
        InWindowGrid.Children.Add(cell3);
        cell3.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
        //cell3.Parent;
        Size result3 = cell3.DesiredSize;
        double height3 = cell3.DesiredSize.Height;
        Debug.WriteLine("height3=" + height3.ToString());
    }
    
    private TextBlock CreateTextBlock()
    {
        TextBlock result = new TextBlock();
        result.Text = "Test Wg";
        result.Padding = new Thickness(2, 1, 2, 1);
        result.VerticalAlignment = VerticalAlignment.Top;
        result.HorizontalAlignment = HorizontalAlignment.Left;
        return result;
    }

Result

height1 = 17,96
height2 = 18
height3 = 17


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source