当我在画布上创建动态图像,然后尝试使用 visualtreehelper.getchild 找到它时,它会找到图像,但偏移量为 0。
如果我使用 xaml 制作图像,它可以工作,但如果我动态创建它,它就不行。如果您动态创建图像而不是在 xaml 中创建图像以使 visualtreehelper.getchild 找到偏移量,您是否需要做一些额外的事情?
Dim iCount As Int16 = 0
'Put Tables on Canvas
For iCount = 0 To 5
Dim tbl As New Image
tbl.Source = New BitmapImage(New Uri("C:/Images/woodtable4.jpg", UriKind.Absolute))
tbl.Width = 50
tbl.Height = 50
tbl.Name = "Tbl" & iCount.ToString
Can1.Children.Add(tbl)
Canvas.SetTop(tbl, 50)
Canvas.SetLeft(tbl, (100 * iCount))
'Can1.RegisterName(tbl.Name, tbl)
Next
'Get Child Objects
Dim x As Int16
Dim y As Int16
For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(Can1) - 1
' Retrieve child visual at specified index value.
Dim childVisual As Visual = CType(VisualTreeHelper.GetChild(Can1, i), Visual)
' Return the offset vector for the TextBlock object.
Dim vector As Vector = VisualTreeHelper.GetOffset(childVisual)
' Convert the vector to a point value.
Dim currentPoint As New Point(VisualOffset.X, VisualOffset.Y)
x = currentPoint.X
y = currentPoint.Y
Next i