I have a TreeView
(I almost copied the same code from XAML Controls Gallary):
<TreeView
x:Name="LocalFolderTreeView"
ItemTemplateSelector="{StaticResource FolderTreeTemplateSelector}"
ItemsSource="{x:Bind Tree, Mode=OneWay}"
Visibility="Collapsed" />
And the XAML of ItemTemplateSelector
:
<DataTemplate x:Key="FolderTemplate" x:DataType="data:FolderTree">
<TreeViewItem
DoubleTapped="FolderTreeItem_DoubleTapped"
IsDoubleTapEnabled="True"
IsExpanded="False"
ItemsSource="{x:Bind Files}">
<StackPanel Orientation="Horizontal">
<StackPanel.ContextFlyout>
<MenuFlyout Opening="OpenPlaylistFlyout" />
</StackPanel.ContextFlyout>
<SymbolIcon Symbol="Folder" />
<TextBlock Margin="0,0,10,0" />
<TextBlock Text="{x:Bind Path}" />
</StackPanel>
</TreeViewItem>
</DataTemplate>
<DataTemplate x:Key="FileTemplate" x:DataType="data:Music">
<TreeViewItem>
<StackPanel
DoubleTapped="FileItem_DoubleTapped"
IsDoubleTapEnabled="True"
Orientation="Horizontal">
<StackPanel.ContextFlyout>
<MenuFlyout Opening="OpenMusicFlyout" />
</StackPanel.ContextFlyout>
<Image Width="20" Source="Assets/colorful_no_bg.png" />
<TextBlock Margin="0,0,10,0" />
<TextBlock Text="{x:Bind Name}" />
</StackPanel>
</TreeViewItem>
</DataTemplate>
<templateselector:FolderTreeTemplateSelector
x:Key="FolderTreeTemplateSelector"
FileTemplate="{StaticResource FileTemplate}"
FolderTemplate="{StaticResource FolderTemplate}" />
C# of ItemTemplateSelector
is
public class FolderTreeTemplateSelector : DataTemplateSelector
{
public DataTemplate FolderTemplate { get; set; }
public DataTemplate FileTemplate { get; set; }
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
if (item is Models.FolderTree) return FolderTemplate;
if (item is Models.Music) return FileTemplate;
return null;
}
}
It is used here
My ViewModels are defined here.
When I add this to the TreeView
, my app crashes. Tree
is not null because I also defined GridView
that allows me to see it.
ItemsSource="{x:Bind Tree, Mode=OneWay}"
What is wrong?
LocalFoldersPage
, I can't find you have set the itemsource for the TreeView. So, I'm not sure the data structure is matched with your xaml. – Nico Zhu - MSFTfolder1
to be your root path if you have music file likefolder1/folder2/music.mp3
. – Seaky Lone