C#Custom Canvas类,ActualHeight / Width始终为0

时间:2015-03-17 16:18:43

标签: c# wpf canvas

我想实现在Canvas上绘制网格的类,但问题是ActualWidthActualHeight设置为0.

enter image description here 帆布就是这个灰色区域。

有人可以告诉我我做错了什么,我是C#的新手。谢谢!

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调用:

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

1 个答案:

答案 0 :(得分:1)

在获取ActualHeight / Width之前需要等待布局传递,尝试在Loaded处理程序中调用ig.DrawGrid。

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();
    }
}

来自FrameWorkElement.ActualHeight

的注释
  

此属性是基于其他高度输入和布局系统的计算值。该值由布局系统本身根据实际渲染过程设置,因此可能略微落后于作为输入更改基础的高度等属性的设置值。

     

因为ActualHeight是一个计算值,所以您应该知道,由于布局系统的各种操作,可能会有多个或增量报告的更改。布局系统可能正在计算子元素所需的度量空间,父元素的约束等等。