简体   繁体   English

父类列表中的数据绑定ListView子类属性

[英]Data Binding ListView child class properties from a list of parent class

I am having problem displaying child class properties through a list of parent class. 我在通过父类列表显示子类属性时遇到问题。

Xaml XAML

<ListView Grid.Row="0" Grid.RowSpan="4" Grid.Column="0" x:Name="lvTest" ItemsSource="{Binding}" ScrollViewer.HorizontalScrollBarVisibility="Auto" SelectionMode="Single" ScrollViewer.VerticalScrollBarVisibility="Auto" Width="630" Height="270">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Index" DisplayMemberBinding="{Binding Path=index}" Width="100" />
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=c.name}" Width="100" />
            <GridViewColumn Header="age" DisplayMemberBinding="{Binding Path=c.age}" Width="100" />
        </GridView>
    </ListView.View>
</ListView>

Code Behind 背后的代码

public partial class MainWindow : Window
{
    List<parent> parentList;

    public MainWindow()
    {
        InitializeComponent();

        GenerateList();

        lvTest.ItemsSource = parentList;
    }

    private void GenerateList()
    {
        parentList = new List<parent>();

        for (int i = 0; i < 10; i++)
        {
            parent p = new parent();
            p.index = i;

            child c = new child();
            c.name = "Name_" + (i + 1).ToString();
            c.age = i;

            parentList.Add(p);
        }
    }
}

Classes

public class parent
{
    public int index { get; set; }
    public child c { get; set; }
}

public class child
{
    public string name { get; set; }
    public int age { get; set; }
}

I can't display the "name" and "age" property of the child class but I have no problem in accessing the index property of the parent class. 我无法显示类的“名称”“年龄”属性,但是访问类的index属性没有问题。

Anyone knows how to do it? 有人知道该怎么做吗?

It's seems you forget to "save" you child instance in parent object: 看来您忘记了在parent对象中“保存”您的child实例:

child c = new child();
c.name = "Name_" + (i + 1).ToString();
c.age = i;

p.c = c; // THIS!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM