从列表 WPF 创建树视图<customClass>



我想从List<PhonesFromStudents>创建一个TreeView

我的自定义类是PhonesFromStudents

public class PhonesFromStudents
{ 
public string Name { get; set; }
public List<string> Phones { get; set; } 
}

XAML 是:

<TreeView  x:Name="tv_source" Grid.Row="2" Grid.Column="1" Margin="0,5" HorizontalAlignment="Stretch" ItemsSource="{Binding ListStudents}" Background="White" BorderBrush="{x:Null}">
<TreeView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"  />
</DataTemplate>
</TreeView.ItemTemplate>
</TreeView>

主视窗.cs

internal MainWindow(List<PhonesFromStudents> list)
{
InitializeComponent();
this.ListStudents = list;
this.DataContext = this;
}

例: 2 名学生 托马斯 - iPhone8,iPhone6 卢卡斯 - iPhone4s, S8

我想要拥有

Thomas
|_____iPhone8
|_____iPhone6
Lucas
|_____iPhone4s
|_____S8

但是我从UI得到一个空列表。 有人可以帮助我吗? 谢谢

使用HierarchicalDataTemplate

<TreeView x:Name="tv_source" Grid.Row="2" Grid.Column="1" Margin="0,5" 
HorizontalAlignment="Stretch" ItemsSource="{Binding ListStudents}" Background="White" BorderBrush="{x:Null}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:PhonesFromStudents}" ItemsSource="{Binding Phones}">
<TextBlock Text="{Binding Name}"  />
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>

。并确保ListStudents是公共财产:

public List<PhonesFromStudents> ListStudents { get; set; }

相关内容

最新更新