我正在学习WPF数据绑定,但我对其中的某些部分还不理解。我在StackOverflow上看到了一些类似的问题,但我仍然无法确定自己做错了什么。
我有一个简单的Person类,其中包含Firstname和Surname属性(标准CLR属性)。我的Window类上也有一个标准CLR属性,用于公开Person实例。
然后我有一些XAML代码,其中有两种绑定方法。第一种方法有效,第二种方法无效。有人能帮我理解为什么第二种方法失败吗?输出日志中没有绑定错误消息。
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="Window1" Height="300" Width="300"
DataContext="{Binding RelativeSource={RelativeSource Self}, Path=MyPerson}">
<StackPanel>
<Label>My Person</Label>
<WrapPanel>
<Label>First Name:</Label>
<Label Content="{Binding RelativeSource={RelativeSource AncestorType=Window, Mode=FindAncestor}, Path=MyPerson.FirstName}"></Label>
</WrapPanel>
<WrapPanel>
<Label>Last Name:</Label>
<Label Content="{Binding MyPerson.Surname}"></Label>
</WrapPanel>
</StackPanel>
编辑:好的,到目前为止谢谢。我把第二个表达式改成了:
<Label Content="{Binding Surname}"></Label>
但我仍然无法使它正常工作!