我在通过父类列表显示子类属性时遇到问题。
的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>
背后的代码
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);
}
}
}
类
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; }
}
我无法显示子类的“name”和“age”属性,但访问时没有问题父类的索引属性。
任何人都知道怎么做?
答案 0 :(得分:1)
您似乎忘记在child
对象中“保存”parent
个实例:
child c = new child();
c.name = "Name_" + (i + 1).ToString();
c.age = i;
p.c = c; // THIS!