powershell – ./images/folder.png as source in WPF

I’m new to PowerShell and WPF. I am creating an app with folder treeview but unable to add the icons for the treeviewitem. I followed this link but unable to show the icons on the treeviewitems. The ObjectTagToImageConverter is working fine but I’m not sure if this path “./images/folder.png” is correct to show the icons. Any assistance you guys can provide would be greatly appreciated.

PowerShell Script

Try { Set-ExecutionPolicy -ExecutionPolicy 'ByPass' -Scope 'Process' -Force -ErrorAction 'Stop' } Catch {}

# Project Root Path
$Global:pathPanel= split-path -parent $MyInvocation.MyCommand.Definition
if ($MyInvocation.MyCommand.CommandType -eq "ExternalScript") { 
    $ScriptPath = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition 
    } else { 
    $ScriptPath = Split-Path -Parent -Path ([Environment]::GetCommandLineArgs()[0]
    ) 
    if (!$ScriptPath){ 
        $ScriptPath = "." 
    } 
}

#Add WPF and Windows Forms assemblies
try{
    Add-Type -AssemblyName PresentationCore,PresentationFramework,WindowsBase,system.windows.forms
    [System.Reflection.Assembly]::LoadWithPartialName('PresentationFramework')
    [System.Reflection.Assembly]::LoadFrom("$ScriptPathassemblySystem.Windows.Interactivity.dll")
    [System.Reflection.Assembly]::LoadFrom("$ScriptPathassemblydev4sys.Tree.dll")
    } catch {
    Write-Verbose $_.Exception.Message
    Throw "Failed to load assemblies."
}

function Import-Xaml-MainPage {
        [xml]$XAMLWindow = $XAMLContent
        $manager = New-Object System.Xml.XmlNamespaceManager -ArgumentList $XAMLWindow.NameTable
        $manager.AddNamespace("x", "http://schemas.microsoft.com/winfx/2006/xaml");
        $xamlReader = New-Object System.Xml.XmlNodeReader $XAMLWindow
        [Windows.Markup.XamlReader]::Load($xamlReader)
    }

function OneDriveBackupTabFolderTreeView {
    
    $dummyNode = $null
    $AllUserFiles  = [IO.Directory]::GetFiles("C:Users")
    $AllUserDirectory = [IO.Directory]::GetDirectories("C:Users")
    
    # ================== Handle Folders ===========================
    foreach ($UserFolder in $AllUserDirectory | Where {$_ -ne "C:UsersAll Users" -And $_ -ne "C:UsersDefault" -And $_ -ne "C:UsersDefault User" -And $_ -ne "C:UsersPublic" -And $_ -NotLike "*.dotnet" -And $_ -NotLike "*.nbi" -And $_ -NotLike "*.oracle_jre_usage" -And $_ -NotLike "*.templateengine"}){
        $treeViewItem = [Windows.Controls.TreeViewItem]::new()
        $treeViewItem.FontSize = "14"
        $treeViewItem.Header = $UserFolder.Substring($UserFolder.LastIndexOf("") + 1)
        $treeViewItem.Tag = @("folder",$UserFolder)
        $treeViewItem.Items.Add($dummyNode) | Out-Null
        $treeViewItem.Add_Expanded({
            Write-Host $_.OriginalSource.Header  " is expanded"
            TreeExpanded($_.OriginalSource)
        })
        $onedriveFolderTreeview.Items.Add($treeViewItem)| Out-Null
        
        $treeViewItem.Add_PreviewMouseLeftButtonDown({
            [System.Windows.Controls.TreeViewItem]$sender = $args[0]
            [System.Windows.RoutedEventArgs]$e = $args[1]
            Write-Host "Left Click: $($sender.Tag)"
        })
        
        $treeViewItem.Add_PreviewMouseRightButtonDown({
            [System.Windows.Controls.TreeViewItem]$sender = $args[0]
            [System.Windows.RoutedEventArgs]$e = $args[1]
            Write-Host "Right Click: $($sender.Tag)"
        })
    }
    
    # ================== Handle Files ===========================
    foreach ($UserFile in $AllUserFiles | Where {$_ -NotLike "*.ini" -And $_ -NotLike "*.lnk" -And $_ -NotLike "*.pst" -And $_ -NotLike "*.DAT" -And $_ -NotLike "*.LOG" -And $_ -NotLike "*.db"}){
        
        $treeViewItem = [Windows.Controls.TreeViewItem]::new()
        $treeViewItem.Header = $UserFile.Substring($UserFile.LastIndexOf("") + 1)
        if ($UserFile | Where {$_ -like "*.csv" -Or $_ -like "*.xlsx" -Or $_ -like "*.xlsm" -Or $_ -like "*.xls"}) {
            $treeViewItem.Tag = @("excel",$UserFile) 
            } elseif ($UserFile | Where {$_ -like "*.docx" -Or $_ -like "*.doc" -Or $_ -like "*.docm" -Or $_ -like "*.dotm"}) {
            $treeViewItem.Tag = @("word",$UserFile) 
            } elseif ($UserFile | Where {$_ -like "*.pptx" -Or $_ -like "*.pptm" -Or $_ -like "*.ppt" -Or $_ -like "*.potm"}) {
            $treeViewItem.Tag = @("powerpoint",$UserFile) 
            } elseif ($UserFile | Where {$_ -like "*.msg"}) {
            $treeViewItem.Tag = @("outlook",$UserFile) 
            } elseif ($UserFile | Where {$_ -like "*.png" -Or $_ -like "*.jpg" -Or $_ -like "*.jpeg" -Or $_ -like "*.jpe" -Or $_ -like "*.jxr" -Or $_ -like "*.gif" -Or $_ -like "*.bmp"}) {
            $treeViewItem.Tag = @("image",$UserFile) 
            } else {
            $treeViewItem.Tag = @("file",$UserFile) 
        }
        $onedriveFolderTreeview.Items.Add($treeViewItem)| Out-Null
        
        $treeViewItem.Add_PreviewMouseLeftButtonDown({
            [System.Windows.Controls.TreeViewItem]$sender = $args[0]
            [System.Windows.RoutedEventArgs]$e = $args[1]
            Write-Host "Left Click: $($sender.Tag)"
        })
        
        $treeViewItem.Add_PreviewMouseRightButtonDown({
            [System.Windows.Controls.TreeViewItem]$sender = $args[0]
            [System.Windows.RoutedEventArgs]$e = $args[1]
            Write-Host "Right Click: $($sender.Tag)"
        })
        
    }
}

Function TreeExpanded($sender){
    
    $dummyNode = $null
    $item = [Windows.Controls.TreeViewItem]$sender
    
    If ($item.Items.Count -eq 1 -and $item.Items[0] -eq $dummyNode)
    {
        $item.Items.Clear();
        Try
        {
            foreach ($string in [IO.Directory]::GetDirectories($item.Tag[1].ToString()) | Where {$_ -NotLike "*.dotnet" -And $_ -NotLike "*.nbi" -And $_ -NotLike "*.oracle_jre_usage" -And $_ -NotLike "*.templateengine"})
            {
                $subitem = [Windows.Controls.TreeViewItem]::new();
                $subitem.Header = $string.Substring($string.LastIndexOf("") + 1)
                $subitem.Tag = @("folder",$string)
                $subitem.Items.Add($dummyNode)
                $subitem.Add_Expanded({
                    TreeExpanded($_.OriginalSource)
                })
                $item.Items.Add($subitem) | Out-Null
                 $subitem.Add_PreviewMouseLeftButtonDown({
                    [System.Windows.Controls.TreeViewItem]$sender = $args[0]
                    [System.Windows.RoutedEventArgs]$e = $args[1]
                    Write-Host "Left Click: $($sender.Tag)"
                })
                $subitem.Add_PreviewMouseRightButtonDown({
                    [System.Windows.Controls.TreeViewItem]$sender = $args[0]
                    [System.Windows.RoutedEventArgs]$e = $args[1]
                    Write-Host "Right Click: $($sender.Tag)"
                })
            }
            
            foreach ($file in [IO.Directory]::GetFiles($item.Tag[1].ToString()) | Where {$_ -NotLike "*.ini" -And $_ -NotLike "*.lnk" -And $_ -NotLike "*.pst" -And $_ -NotLike "*.DAT" -And $_ -NotLike "*.LOG" -And $_ -NotLike "*.db"}){
                $subitem = [Windows.Controls.TreeViewItem]::new()
                $subitem.Header = $file.Substring($file.LastIndexOf("") + 1)
                
                if ($file | Where {$_ -like "*.csv" -Or $_ -like "*.xlsx" -Or $_ -like "*.xlsm" -Or $_ -like "*.xls"}) {
                    $subitem.Tag = @("excel",$file) 
                    } elseif ($file | Where {$_ -like "*.docx" -Or $_ -like "*.doc" -Or $_ -like "*.docm" -Or $_ -like "*.dotm"}) {
                    $subitem.Tag = @("word",$file) 
                    } elseif ($file | Where {$_ -like "*.pptx" -Or $_ -like "*.pptm" -Or $_ -like "*.ppt" -Or $_ -like "*.potm"}) {
                    $subitem.Tag = @("powerpoint",$file) 
                    } elseif ($file | Where {$_ -like "*.msg"}) {
                    $subitem.Tag = @("outlook",$file) 
                    } elseif ($file | Where {$_ -like "*.png" -Or $_ -like "*.jpg" -Or $_ -like "*.jpeg" -Or $_ -like "*.jpe" -Or $_ -like "*.jxr" -Or $_ -like "*.gif" -Or $_ -like "*.bmp"}) {
                    $subitem.Tag = @("image",$file) 
                    } else {
                    $subitem.Tag = @("file",$file) 
                }
                $item.Items.Add($subitem)| Out-Null
                $subitem.Add_PreviewMouseLeftButtonDown({
                    [System.Windows.Controls.TreeViewItem]$sender = $args[0]
                    [System.Windows.RoutedEventArgs]$e = $args[1]
                    Write-Host "Left Click: $($sender.Tag)"
                })
                $subitem.Add_PreviewMouseRightButtonDown({
                    [System.Windows.Controls.TreeViewItem]$sender = $args[0]
                    [System.Windows.RoutedEventArgs]$e = $args[1]
                    Write-Host "Right Click: $($sender.Tag)"
                })
            }
        }   
        Catch [Exception] { }
    }
    
}
OneDriveBackupTabFolderTreeView
$MainPageWindow.ShowDialog() | Out-Null

WPF

<Window x:Name="wpfWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:Controls1="clr-namespace:System;assembly=mscorlib"
    xmlns:s="clr-namespace:System;assembly=mscorlib"
    xmlns:sys="clr-namespace:dev4sys.Tree;assembly=dev4sys.Tree"
    Width="848"
    Height="573"
    Background="White"
    Icon="file:///sourceLogoMain"
    ResizeMode="CanMinimize"
    Title="Title"
    WindowStartupLocation="CenterScreen" Topmost="True">
        <Grid>
            <Label Content="" Height="57" Margin="0,1,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Top" Grid.Column="0" Grid.Row="0">
                <Label.Background>
                    <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                        <LinearGradientBrush.GradientStops>
                            <GradientStop Offset="0.79045092838196285" Color="#FF031438" />
                            <GradientStop Offset="1" Color="#FFFFFFFF" />
                        </LinearGradientBrush.GradientStops>
                    </LinearGradientBrush>
                </Label.Background>
            </Label>
            <Label Height="42" Margin="78,9,21,0" HorizontalAlignment="Stretch" VerticalAlignment="Top" Background="{x:Null}" Grid.Column="0" Grid.Row="0" />
            <Label Content="Title" Width="367" Height="42" Margin="0,9,419.5,0" HorizontalAlignment="Right" VerticalAlignment="Top" Background="{x:Null}" FontSize="20" Foreground="#FFF9FAFC" Grid.Column="0" Grid.Row="0" />
            <Image Width="39" Height="36" Margin="11,12,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Source="file:///sourceLogoMain" Grid.Column="0" Grid.Row="0" />
            <TabControl Width="813" Height="458" Margin="11,66,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Column="0" Grid.Row="0">
                <TabControl.Resources>
                    <Style TargetType="TabItem">
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="TabItem">
                                    <Grid Name="Panel">
                                        <ContentPresenter x:Name="ContentSite" Margin="15,5" HorizontalAlignment="Center" VerticalAlignment="Center" ContentSource="Header" />
                                    </Grid>
                                    <ControlTemplate.Triggers>
                                        <Trigger Property="IsSelected" Value="True">
                                            <Setter Property="Background" TargetName="Panel" Value="LightGreen" />
                                            <Setter Property="HeaderTemplate">
                                                <Setter.Value>
                                                    <DataTemplate>
                                                        <TextBlock FontWeight="Bold" Text="{Binding}" />
                                                    </DataTemplate>
                                                </Setter.Value>
                                            </Setter>
                                        </Trigger>
                                        <Trigger Property="IsSelected" Value="False">
                                            <Setter Property="Background" TargetName="Panel" Value="LightSkyBlue" />
                                            <Setter Property="FontWeight" Value="Normal" />
                                        </Trigger>
                                    </ControlTemplate.Triggers>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </TabControl.Resources>
                <TabControl.Effect>
                    <DropShadowEffect />
                </TabControl.Effect>
                <TabItem x:Name="backupTab" Cursor="Hand" FontSize="12" FontWeight="Normal" Header="Backup User Data (OneDrive)" Visibility="Visible">
                    <TabItem.Effect>
                        <DropShadowEffect />
                    </TabItem.Effect>
                    <Canvas>
                        <GroupBox Width="275"  Height="122"  BorderBrush="#FF0400F2" BorderThickness="2,2,2,2" Cursor="Arrow" FontWeight="Bold" Foreground="Black" Header="Connect to OneDrive Admin" Canvas.Left="9" Canvas.Top="13">
                            <Canvas>
                                <Label Content="Email Address" Width="92" Height="26" FontSize="10" Canvas.Left="6" Canvas.Top="0" />
                                <Label x:Name="connectOneDriveLabel" Content="Failed" Width="135" Height="25" HorizontalContentAlignment="Center" Background="#FFFF002E" FontSize="12" Visibility="Hidden" Canvas.Left="125" Canvas.Top="-3.5" />
                            </Canvas>
                        </GroupBox>
                        <Button x:Name="connectOneDriveButton" Content="Connect" Width="132" Height="28" FontFamily="Segoe UI" FontSize="13" FontWeight="Bold" IsEnabled="False" Canvas.Left="62.5" Canvas.Top="96" />
                        <Image x:Name="connectOneDriveIcon" Width="34" Height="28" Cursor="Arrow" Source="file:///sourceConnectedOneDriveIcon" Canvas.Left="199" Canvas.Top="96" />
                        <TextBox x:Name="connectOneDriveTextBox" Width="241" Height="20" BorderBrush="#FF020000" BorderThickness="0,0,0,2" Cursor="Pen" Canvas.Left="26" Canvas.Top="62" />
                        <GroupBox Width="505" Height="405" BorderBrush="#FF0400F2" BorderThickness="2,2,2,2" Cursor="Arrow" FontWeight="Bold" Foreground="Black" Header="Select Folders to Backup" Canvas.Left="294" Canvas.Top="13" />
                        <TreeView x:Name="onedriveFolderTreeview" Width="489" Height="367" BorderBrush="{x:Null}" Canvas.Left="302" Canvas.Top="45">
                            <TreeView.Resources>
                                <Style TargetType="{x:Type TreeViewItem}">
                                    <Setter Property="HeaderTemplate">
                                        <Setter.Value>
                                            <HierarchicalDataTemplate>
                                                <StackPanel Orientation="Horizontal">
                                                    <CheckBox x:Name="onedriveFolderFileCheckBox"/>
                                                    <Image Width="20" Height="20" Stretch="Fill" Margin="5,0"
                                                    Source="{Binding
                                                    RelativeSource={RelativeSource
                                                    Mode=FindAncestor,
                                                    AncestorType={x:Type TreeViewItem}},
                                                    Path=Tag,
                                                    Converter={sys:ObjectTagToImageConverter}}"/>
                                                    <TextBlock Text="{Binding}" Margin="10,0"/>
                                                </StackPanel>
                                            </HierarchicalDataTemplate>
                                        </Setter.Value>
                                    </Setter>
                                </Style>
                            </TreeView.Resources>
                        </TreeView>
                    </Canvas>
                </TabItem>
                <TabItem x:Name="removeUserTab" Cursor="Hand" FontWeight="Normal" Header="Remove User Profile">
                    <TabItem.Effect>
                        <DropShadowEffect />
                    </TabItem.Effect>
                    <Canvas />
                </TabItem>
                <TabItem x:Name="uninstallAppTab" Cursor="Hand" FontSize="12" FontWeight="Normal" Header="Uninstall Applications">
                    <TabItem.Effect>
                        <DropShadowEffect />
                    </TabItem.Effect>
                    <Canvas />
                </TabItem>
                <TabItem x:Name="removeDomainTab" Cursor="Hand" FontSize="12" FontWeight="Normal" Header="Remove From Domain">
                    <TabItem.Effect>
                        <DropShadowEffect />
                    </TabItem.Effect>
                    <Canvas />
                </TabItem>
            </TabControl>
        </Grid>
    </Window>

WPF Window

Leave a Comment