locked
Why the Canvas size is set to 0 (zero) after making it a children of a StackPanel defined in XAML?

    Question

  • Why the Canvas size is set to 0 (zero) after making it a children of a StackPanel defined in XAML?

    1.        Test1
      1.        Create a canvas, set its size and then add it to the StackPanelDefinedInXAML.
      2.       After making it a child of the StackPanelDefinedInXAML, canvas.ActualWidth=0 and canvas.ActualHeight=0;
    2.        Test2
      1.        Create a canvas, set its size and then add it to a StackPanelDefinedInCode
      2.       After making it a child of the StackPanelDefinedInCode, canvas.ActualWidth=5000 and canvas.ActualHeight=5000;

    Why Test1 resets the size of the canvas and Test2 doesn’t reset the size of the canvas?

        <ScrollViewer Name="Scroller">
            <StackPanel Name="PanelDefinedInXAML" />
        </ScrollViewer>

        public sealed partial class MainPage : Page
        {
            public MainPage()
            {
                this.InitializeComponent();
            }

            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
                FirstPage.Loaded += FirstPage_Loaded;
            }

            private void FirstPage_Loaded(object sender, RoutedEventArgs e)
            {
                Test1();
                Test2();
            }

            private void Test1()
            {
                Canvas canvas = new Canvas();
                canvas.Width = 5000;
                canvas.Height = 5000;

                PanelDefinedInXAML.Children.Add(canvas);
            }

            private void Test2()
            {
                Canvas canvas = new Canvas();
                canvas.Width = 5000;
                canvas.Height = 5000;

                StackPanel panelDefinedInCode = new StackPanel();
                Scroller.Content = panelDefinedInCode;

                panelDefinedInCode.Children.Add(canvas);
            }


    Wednesday, March 13, 2013 5:16 AM

Answers

  • FrameworkElement.ActualHeight property (Windows) documents the 'Actual' values: please read carefully. ActualHeight and ActualWidth values are a result of the rendering pass [which follows the Measuring and the Arranging passes]. In your test case, this occurs following 2 different scenarios which explain the observed values.

    As a general rule, it is strongly advised to develop applications that rely as less as possible on 'Actua'l values. Refer to them on canvas.LayoutUpdated [e.g.] event handling if absolutely necessary.

    Note: Don't forget to post future C#/XAML questions in the relevant forum. Thank you

    • Marked as answer by Jesse Jiang Monday, March 18, 2013 2:33 AM
    Wednesday, March 13, 2013 6:31 AM