代码之家  ›  专栏  ›  技术社区  ›  Matt B

WPF数据绑定到代码隐藏中的标准CLR属性

  •  3
  • Matt B  · 技术社区  · 16 年前

    只是学习WPF数据绑定,在我的理解上有差距。我在StackOverflow上看到过一些类似的问题,但我仍在努力确定自己做错了什么。

    我有一个简单的Person类,具有Firstname和姓氏属性(标准CLR属性)。我的Window类上还有一个标准的CLR属性,它公开了Person的一个实例。

    有人能帮我理解为什么第二种方法失败吗?输出日志中没有绑定错误消息。

    <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 回复  |  直到 16 年前
        1
  •  2
  •   Matt B    16 年前

    在后面的代码中,我正在设置MyPerson属性 之后

    我使用的第一个方法之所以有效,是因为在初始化标签并计算其数据绑定表达式时,窗口已经初始化,MyPerson属性已经设置。

        2
  •  1
  •   Craig Suchanec    16 年前

    首先,除非在绑定上设置诊断,否则大多数情况下不会看到绑定错误。第二个不起作用的原因是您已经将DataContext设置为MyPerson。因为这是DataContext,所以您需要做的就是绑定到属性姓氏。你现在的做法是试着叫MyPerson.MyPerson.lasname。

        3
  •  1
  •   Dave Arkell    16 年前

    对于第二种方法,您只需要

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

    TopDataContext适合我,但是绑定不会出现在设计器中,除非我有一个包含数据的单独类。为了让它发挥作用,你可以这样做:

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

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

    我认为这在设计器中是有效的,因为我在xaml中显式地创建了类的新实例。

        4
  •  0
  •   MojoFilter    16 年前

    处理第一个绑定的另一个简单方法是为窗口指定一个名称并通过引用它 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>