Why are ActualWidth and ActualHeight 0.0 in this case?

南楼画角 提交于 2019-11-26 15:23:57
Ray Burns

ActualHeight and ActualWidth are not set until the control is measured and arranged. Usually there is nothing in InitializeComponent() that causes a measure, so when it returns these will still be zero.

You can force these to be computed earlier by simply calling the window's Measure() and Arrange() methods manually after the window's InitializeComponent() returns.

If you are sizing to content:

window.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
window.Arrange(new Rect(0, 0, window.DesiredSize.Width, window.DesiredSize.Height));

If you are using an explicit window size:

window.Measure(new Size(Width, Height));
window.Arrange(new Rect(0, 0, window.DesiredSize.Width, window.DesiredSize.Height));
Kent Boogaart

Ray is correct (+1) that this is due to the fact that the measure and arrange pass has not executed yet. However, rather than force another layout pass (expensive), you can just wait until your control has loaded before accessing the ActualXxx properties:

public MyWindow()
{
    Loaded += delegate
    {
        // access ActualWidth and ActualHeight here
    };

}

In our case the solution was simple, as everybody said ActualWidth and ActualHeight needed to get called after the Loaded even completes, So we just wrapped the code in a dispatcher and set the priority to Loaded as below:

Dispatcher.Invoke(new Action(() =>
{
   graphHeight = ActualHeight;
   graphWidth = ActualWidth;
}), DispatcherPriority.Loaded);
Rahul Saksule

ActualWidth and ActualHeight are available only after XAML loading completed,before loading how can you find these parameters?

Use Loaded event and inside it do find the ActualWidth and ActualHeight.

private void me_Loaded(object sender, RoutedEventArgs e)
{
  // do your stuffs here.
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!