WPF DataBinding到代码隐藏中的标准CLR属性

时间:2010-05-28 11:23:44

标签: wpf data-binding xaml

只是学习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>

我仍然无法让它工作!

4 个答案:

答案 0 :(得分:2)

好的,我在这里发现了问题。 WPF的新手,所以我花了一段时间才弄明白。

在后面的代码中我在调用InitializeComponent之后设置了MyPerson属性

我使用的第一个方法是有效的,因为Window已初始化,MyPerson属性在标签初始化时设置,并且它的数据绑定表达式已经过评估。

第二种方法不起作用,因为在Window和关联的DataContext初始化时尚未设置MyPerson属性。

当你知道怎么做时很简单!

答案 1 :(得分:1)

要使用第二种方法,您只需要

<Label Content="{Binding Surname}"/>

因为您已经将DataContext设置为顶部窗口元素中的人物。

top datacontext对我有用,但是绑定没有显示在设计器中,除非我有一个包含数据的单独类。为此,您可以执行以下操作:

<Window.Resources>
    <local:BindingClass x:Key="bindingClass"/>
</Window.Resources>
<Grid DataContext="{StaticResource bindingClass.MyPerson}">
    <Label Content="{Binding Surname}"/>
</Grid>

这要求您创建一个包含MyPerson属性的单独类(在本例中称为BindingClass)。

我认为这适用于设计器,因为我在xaml中明确地创建了一个类的新实例。

答案 2 :(得分:1)

首先,除非您对该绑定设置诊断,否则大多数情况下您不会看到绑定错误。第二个不起作用的原因是您已将DataContext设置为MyPerson。由于这是DataContext,您需要做的就是绑定属性Surname。你现在的方式是试图调用MyPerson.MyPerson.Surname。

答案 3 :(得分:0)

处理第一个绑定的另一个简单方法是给你的Window命名并在绑定中通过ElementName引用它:

<Window x:Class="WpfApplication1.Window1"
    Name="MyWindow"
    ...>
<StackPanel>
    <Label>My Person</Label>
    <WrapPanel>
        <Label>First Name:</Label>
        <Label Content="{Binding Path=MyPerson.FirstName, ElementName=MyWindow}"></Label>
    </WrapPanel>
    <WrapPanel>
        <Label>Last Name:</Label>
        <Label Content="{Binding MyPerson.Surname}"></Label>
    </WrapPanel>
</StackPanel>