在我的程序中,我正在动态创建要添加到 WPF 窗口中的画布中的图像。我的问题是:如何将 canvas.left 和 canvas.right 点绑定到类属性。
如果图像在运行时之前存在,我会在 XAML/WPF 中像这样制作和绑定它:
<Image Height="26" HorizontalAlignment="Left" Canvas.Left="{Binding left}" Canvas.Top="{Binding top}" Name="Image1" Stretch="Fill" VerticalAlignment="Top" Width="28" Source="/imageTest;component/Images/blue-pin-md.png" />
我在 VB.net 中有什么:
'Create array of images
Dim myImages(5) as myImage
For i = 0 to myImages.count - 1
myImages(i) = New myImage
'set datacontext if I can bind
myImages(i).image.DataContext = myImages(i)
canvas1.Children.Add(myImages(i).image)
Next
我的图像类:
Imports System.ComponentModel
Public Class myImage
Implements INotifyPropertyChanged
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Private Sub NotifyPropertyChanged(ByVal info As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
End Sub
Private Property _image as New Image
Private Property _left As Double
Private Property _top As Double
Private Shared Property r As New Random()
Public Sub New()
_image.Width = 28
_image.Height = 26
_image.Source = New System.Windows.Media.Imaging.BitmapImage(New Uri("/imageTest;component/Images/blue-pin-md.png", UriKind.Relative))
'the below works without binding if I just want to set and leave them in one place but I would like to bind them so that I can move them relative to other data
'_left = r.Next(0, System.Windows.SystemParameters.PrimaryScreenWidth)
'_top = r.Next(0, System.Windows.SystemParameters.PrimaryScreenHeight)
End Sub
Public ReadOnly Property image As Image
Get
Return _image
End Get
End Property
Public ReadOnly Property left As Double
Get
Return _left
End Get
End Property
Public ReadOnly Property top As Double
Get
Return _top
End Get
End Property
'a possible move method that would take advantage of the binding
Public Sub move()
_top += 1
_left += 1
NotifyPropertyChanged("left")
NotifyPropertyChanged("top")
End Sub