Matjaž
Matjaž

Reputation: 2115

C# Custom Canvas class, ActualHeight/Width are always 0

I want to implement class that draw grid on Canvas, but problem is that ActualWidth and ActualHeight are set to 0.

enter image description here Canvas is all this gray area.

Can someone tell me what I'm doing wrong, I'm newbie in C#. Thanks!

class ImageGrid : Canvas
{
    private double GridSize = 50;

    public ImageGrid()
    {
        Background = new SolidColorBrush(Colors.DarkGray);
    }

    public void  DrawGrid()
    {

        Children.Clear();

        #region Draw image
        // TODO - Draw image
        #endregion

        #region Draw grid

        for ( double x = 0; x < ActualWidth; x+=GridSize )
        {
            Line line = new Line();
            line.X1 = x;
            line.X2 = x;
            line.Y1 = 0;
            line.Y2 = ActualWidth;              // Why 0 ?
            line.Stroke = Brushes.Black;
            line.StrokeThickness = 1;
            Children.Add(line);
        }

        for ( double y = 0; y < ActualHeight; y += GridSize )
        {
            Line line = new Line();
            line.X1 = 0;
            line.X2 = ActualHeight;             // Why 0 ?
            line.Y1 = y;
            line.Y2 = y;
            line.Stroke = Brushes.Black;
            line.StrokeThickness = 1;
            Children.Add(line);
        }

        #endregion

    }

}

ImageGrid call:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        ImageGrid ig = new ImageGrid();
        Grid.Children.Add(ig);
        ig.DrawGrid();
    }
}

Upvotes: 0

Views: 1067

Answers (1)

Bilal Bashir
Bilal Bashir

Reputation: 1493

You need to wait for the layout pass before getting the ActualHeight/Width, try calling ig.DrawGrid in the Loaded handler.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        ImageGrid ig = new ImageGrid();
        Grid.Children.Add(ig);
        ig.Loaded += ImageGrid_Loaded;
       
    }
    void ImageGrid_Loaded(object sender, RoutedEventArgs e)
    {
         ig.DrawGrid();
    }
}

Note from FrameWorkElement.ActualHeight

This property is a calculated value based on other height inputs, and the layout system. The value is set by the layout system itself, based on an actual rendering pass, and may therefore lag slightly behind the set value of properties such as Height that are the basis of the input change.

Because ActualHeight is a calculated value, you should be aware that there could be multiple or incremental reported changes to it as a result of various operations by the layout system. The layout system may be calculating required measure space for child elements, constraints by the parent element, and so on.

Upvotes: 1

Related Questions