Silverlight / WPF绑定嵌套对象

时间:2014-10-15 16:06:53

标签: wpf silverlight data-binding

MyViewModel的实例设置为.Xaml文件的DataContext。数据绑定如下,但不显示{FName1,FName2,LName1,LName2}的文本。仅显示(ThePerson)的文本。感谢任何人有建议解决它。

.xaml文件

<StackPanel> 
    <TextBlock x:Name="ThePerson" Text="{Binding PersonOne}" />
    <TextBlock x:Name="FName1" Text="{Binding PersonOne.FirstName}" />
    <TextBlock x:Name="FName2" Text="{Binding Person.FirstName}" />
    <TextBlock x:Name="LName1" Text="{Binding Path=PersonOne.LastName}" />
    <TextBlock x:Name="LName2" Text="{Binding Path=Person.LastName}" />
</StackPanel>

ViewModel文件

public class MyViewModel {
    public MyViewModel()
    {
        PersonOne = new Person()
        {
            FirstName = "James",
            LastName = "San"
        };
    }
    public Person PersonOne { get; set; }
}

public class Person {
    public string FirstName;
    public string LastName;
    public override string ToString()
    {
        return string.Format("{0}, {1}", LastName, FirstName);
    }
}

1 个答案:

答案 0 :(得分:0)

您需要将FirstName等作为Person类的属性而不是字段。为它们添加一个getter和setter。您只能绑定到属性。