Universal Windows Platform – FileView App

FileView App shows how to create a simple application that uses the FolderPicker and TreeView Control

Step 1

If not already, follow Setup and Start on how to Install and get Started with Visual Studio 2017 or in Windows 10 choose Start, and then from the Start Menu find and select Visual Studio 2017.

vs2017

Step 2

Once Visual Studio Community 2017 has started, from the Menu choose File, then New then Project…

vs2017-file-new-project

Step 3

From New Project choose Visual C# from Installed, Templates then choose Blank App (Universal Windows) and then type in the Name as FileViewApp and select a Location and then select Ok to create the Project
vs2017-new-project-fileview-app

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10, version 1803 (10.0; Build 17134) which is the April 2018 Update and the Minimum Version to be the same.

vs2017-target-platform

The Target Version will control what features your application can use in Windows 10 so by picking the most recent version you’ll be able to take advantage of those features. To make sure you always have the most recent version, in Visual Studio 2017 select Tools Extensions and Updates… then and then see if there are any Updates

Step 5

Once done select from the Menu, Project, then Add New Item…

vs2017-project-add-new-item

Step 6

From the Add New Item window select Visual C#, then Code from Installed then select Code File from the list, then type in the Name as Library.cs before selecting Add to add the file to the Project

vs2017-add-new-item-fileview-app

Step 7

Once in the Code View for Library.cs the following should be entered:

using System;
using System.Collections.Generic;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI.Xaml.Controls;

namespace FileViewApp
{
    public class FileViewItem
    {
        public string Name { get; set; }
        public string Path { get; set; }
    }

    public class Library
    {
        private async void FillNode(TreeViewNode node)
        {
            StorageFolder folder = null;
            if (node.Content is StorageFolder && node.HasUnrealizedChildren)
            {
                folder = (StorageFolder)node.Content;
            }
            else
            {
                return;
            }
            IReadOnlyList<IStorageItem> list = await folder.GetItemsAsync();
            if (list.Count == 0) return;
            foreach (IStorageItem item in list)
            {
                TreeViewNode itemNode = new TreeViewNode
                {
                    Content = item
                };
                if (item is StorageFolder)
                {
                    itemNode.HasUnrealizedChildren = true;
                }
                node.Children.Add(itemNode);
            }
            node.HasUnrealizedChildren = false;
        }

        public void Expanding(TreeViewNode node)
        {
            if (node.HasChildren) FillNode(node);
        }

        public void Collapsed(TreeViewNode node)
        {
            node.Children.Clear();
            node.HasUnrealizedChildren = true;
        }

        public FileViewItem Invoked(TreeViewNode node)
        {
            FileViewItem item = null;
            if (node.Content is IStorageItem storageItem)
            {
                item = new FileViewItem()
                {
                    Name = storageItem.Name,
                    Path = storageItem.Path
                };
                if (node.Content is StorageFolder)
                {
                    node.IsExpanded = !node.IsExpanded;
                }
            }
            return item;
        }

        public async void Folder(TreeView tree)
        {
            try
            {
                FolderPicker picker = new FolderPicker()
                {
                    SuggestedStartLocation = PickerLocationId.PicturesLibrary
                };
                picker.FileTypeFilter.Add("*");
                IStorageFolder folder = await picker.PickSingleFolderAsync();
                if (folder != null)
                {
                    tree.RootNodes.Clear();
                    TreeViewNode node = new TreeViewNode
                    {
                        Content = folder,
                        IsExpanded = true,
                        HasUnrealizedChildren = true
                    };
                    tree.RootNodes.Add(node);
                    FillNode(node);
                }
            }
            finally
            {
                // Ignore Exceptions
            }
        }
    }
}

In the Code File for Library there are using statements to include the necessary functionality. There is a FileViewItem with Properties for Name and Path

The Library Class has a FillNode Method which will help populate the TreeView Control by going through any Folder Childen as StorageFolder to find more of them until all the IStorageItem for all StorageFolder have been found. The Expanding Method is used to call the FillNode Method and Collapsed will be used to remove Children from a TreeViewNode. The Invoked Method is used to set a FileViewItem based on a TreeViewNode and the Folder Method is used with a FolderPicker to select an IStorageFolder with PickSingleFolderAsync and then it will set a Root TreeViewNode as the starting point for the TreeView and then call the FillNode Method.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-fileview-app

Step 9

From the Menu choose View and then Designer

vs2017-view-designer

Step 10

The Design View will be displayed along with the XAML View and in this above the Grid element, enter the following XAML:

<Page.Resources>
	<DataTemplate x:Key="TreeViewItemTemplate">
		<TextBlock Text="{Binding Content.DisplayName}"
		HorizontalAlignment="Left" VerticalAlignment="Center"
		Style="{ThemeResource BodyTextBlockStyle}"/>
	</DataTemplate>
	<Style TargetType="TreeView">
		<Setter Property="Template">
			<Setter.Value>
				<ControlTemplate TargetType="TreeView">
					<TreeViewList x:Name="ListControl"
					ItemTemplate="{StaticResource TreeViewItemTemplate}"
					ItemContainerStyle="{StaticResource TreeViewItemStyle}"
					CanDragItems="True" AllowDrop="True" CanReorderItems="False">
					</TreeViewList>
				</ControlTemplate>
			</Setter.Value>
		</Setter>
	</Style>
</Page.Resources>

Then while still in the XAML View between the Grid and /Grid elements, enter the following XAML:

<SplitView IsPaneOpen="True" DisplayMode="Inline">
	<SplitView.Pane>
		<TreeView x:Name="Display" SelectionMode="Single"
		Expanding="TreeView_Expanding" Collapsed="TreeView_Collapsed"
		ItemInvoked="TreeView_ItemInvoked"/>
	</SplitView.Pane>
	<StackPanel Margin="10">
		<TextBlock Text="Name:"/>
		<TextBlock Name="FileName" FontWeight="SemiBold"/>
		<TextBlock Text="Path:"/>
		<TextBlock Name="FilePath" FontWeight="SemiBold"/>
	</StackPanel>
</SplitView>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Icon="OpenLocal" Label="Folder" Click="Folder_Click"/>
</CommandBar>

Within the Page.Resources block of XAML above the Grid Element contains DataTemplate for the TreeView which contains a TextBlock and a Style for the TreeView which contains a ControlTemplate to set the look-and-feel of the TreeView accordingly.

Within the main Grid Element, the first block of XAML is a SplitView Control which contains an TreeView within the Pane annd a StackPanel in the main content which contains TextBlock Controls to display information about a selected File or Folder. The second block of XAML is a CommandBar with AppBarButton for Folder which calls Folder_Click.

Step 11

From the Menu choose View and then Code

vs2017-view-code

Step 12

Once in the Code View, below the end of public MainPage() { … } the following Code should be entered:

Library library = new Library();

private void TreeView_Expanding(TreeView sender, TreeViewExpandingEventArgs args)
{
	library.Expanding(args.Node);
}

private void TreeView_Collapsed(TreeView sender, TreeViewCollapsedEventArgs args)
{
	library.Collapsed(args.Node);
}

private void TreeView_ItemInvoked(TreeView sender, TreeViewItemInvokedEventArgs args)
{
	FileViewItem item = library.Invoked((TreeViewNode)args.InvokedItem);
	FileName.Text = item.Name;
	FilePath.Text = item.Path;
}

private void Folder_Click(object sender, RoutedEventArgs e)
{
	library.Folder(Display);
}

There is an TreeView_Expanding, TreeView_Collapsed and TreeView_ItemInvoked Event Handler which will handle different Events from the TreeView Control along with TreeView_ItemInvoked which will get the FileViewItem to be displayed. There is a Folder_Click Event Handler which calls the Folder Method in the Library Class.

Step 13

That completes the Universal Windows Platform Application so Save the Project then in Visual Studio select the Local Machine to run the Application

vs2017-local-machine

Step 14

Once the Application has started running you can tap on the Open Button to to select any Folder which itself and any Child Folders will be displayed in the TreeView along with some basic information about any selected Files or Folders of the TreeView will be displayed also

uwp-ran-fileview-app

Step 15

To Exit the Application select the Close button in the top right of the Application

vs2017-close

This example was inspired from the TreeView example from docs.microsoft.com which has been expanded to allow the selection of any Folder using a FolderPicker

Creative Commons License

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s