从另一个类在WPF中绘制矩形到屏幕

时间:2015-01-27 15:44:57

标签: c# wpf vb.net

所以我在主类中有一个类Pillar的方法,它创建两个矩形并设置它们的宽度和高度。然后我尝试使用Canvas.SetTop将它们绘制到屏幕上。

'Main

'place rectangles
Canvas.SetTop(pillar.top, 0)
Canvas.SetBottom(pillar.bottom, 0)

Canvas.SetLeft(pillar.top, 100)
Canvas.SetLeft(pillar.bottom, 100)

这是支柱类

Class Pillar
    Property Right As Integer
    Public top, bottom As Rectangle
    Private gap As Integer = 60
    Private _width = 100
    Private gapPos As Integer

    Public Sub New()
        top = New Rectangle
        bottom = New Rectangle

        top.Width = _width
        bottom.Width = _width

        gapPos = CInt(Math.Ceiling(Rnd() * 80)) + 470

        top.Height = gapPos - (gap / 2)
        bottom.Height = gapPos - (gap / 2)

        top.Fill = New SolidColorBrush(Color.FromRgb(255, 255, 255))
        bottom.Fill = New SolidColorBrush(Color.FromRgb(255, 255, 255))
    End Sub
End Class

问题是没有在屏幕上绘制矩形,而程序不会抛出任何错误。

1 个答案:

答案 0 :(得分:0)

Canvas.SetTop/Bottom/Left/Right()不会在屏幕上绘制某些内容,而是定位已在屏幕上显示的元素。所以,在致电

之前
Canvas.SetTop(pillar.top, 0)

尝试将rectange添加到画布,例如通过调用

myCanvas.Children.Add(pillar.top)