我创建了一个 UserControl 并在代码隐藏中添加了一个新类:
Public WithEvents Fridolin As New Frog With {.Location = New Point(11, 22)}
Public Class Frog
Implements INotifyPropertyChanged
Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
Private Sub NotifyPropertyChanged(Optional ByVal propertyName As String = Nothing)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
Dim _location As Point
Property Location As Point
Get
Return _location
End Get
Set(value As Point)
_location = value
NotifyPropertyChanged("Location")
End Set
End Property
End Class
如您所见,还有一个 Frog 实例。现在,在我的 XAML 中有一个 Path 对象,我想将它绑定到对象“Fridolin”的 Location 属性。
这是我的 XAML
<UserControl x:Class="ucFrogup"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:app="clr-namespace:resi_estimate"
mc:Ignorable="d"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
d:DesignHeight="360" d:DesignWidth="640">
<UserControl.Resources>
<ResourceDictionary>
<StreamGeometry x:Key="ProtoLeaf" >m 451.45 512 c 17.06 0 30.43 -13.86 30.43 -31.56 V 31.55 C 481.87 13.86 468.51 0 451.44 0 A 32.94 32.94 0 0 0 434.99 4.52 L 46.29 229 c -10.13 5.85 -16.18 16 -16.18 27 0 11 6 21.2 16.18 27 l 388.7 224.48 a 32.92 32.92 0 0 0 16.45 4.52 z</StreamGeometry>
<StreamGeometry x:Key="ProtoFrog">m 51.45 512 c 17.06 0 30.43 -13.86 30.43 -31.56 V 31.55 C 481.87 13.86 468.51 0 451.44 0 A 32.94 32.94 0 0 0 434.99 4.52 L 46.29 229 c -10.13 5.85 -16.18 16 -16.18 27 0 11 6 21.2 16.18 27 l 388.7 224.48 a 32.92 32.92 0 0 0 16.45 4.52 z</StreamGeometry>
</ResourceDictionary>
</UserControl.Resources>
<Grid>
<Viewbox Margin="97,10,10,10">
<Canvas x:Name="Pond" Background="#FF58CFF1" Margin="4" Height="360" Width="640">
<Path x:Name="Froggy" Height="80" Width="80" Canvas.Left="{Binding Source=Fridolin, Path=Location.X}" Canvas.Top="{Binding Source=Fridolin, Path=Location.Y}" Stretch="Uniform" Fill="#FF43B231" Data="{DynamicResource ProtoFrog}"/>
</Canvas>
</Viewbox>
<Button x:Name="btnGo" Content="Go" HorizontalAlignment="Left" VerticalAlignment="Top" Height="34" Width="78" ></Button>
</Grid>
我错过了什么?顺便说一句,我收到此错误消息:
System.Windows.Data Error: 40 : BindingExpression path error: 'Location' property not found on 'object' ''String' (HashCode=-1218894399)'. BindingExpression:Path=Location.Y; DataItem='String' (HashCode=-1218894399); target element is 'Path' (Name='Froggy'); target property is 'Top' (type 'Double')
我不确定您的代码背后发生了什么,但根据我所知道的,请执行以下操作:
Canvas.Left="{Binding Path=Fridolin.Location.X}"
this.DataContext = this;
第 2 步可能是可选的,因为我不记得 DataContext 是否已经分配给它自己。
这将为您与ucFrogup
对象本身的所有绑定设置 DataContext ,从而使您能够在不指定源的情况下进行绑定。源用于绑定到(其他)UI 元素,而不是属性。
我建议任何想要使用 WPF 的人阅读 MVVM 模式。它使绑定更加简单和易于阅读。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句