Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

PowerShell WPF XAML multibinding datacontext template example - Part 4

Article Series
PowerShell WPF XAML simple data binding datacontext example - Part 1
PowerShell WPF XAML control to control data binding datacontext example - Part 2
PowerShell WPF XAML DataGrid control databinding datacontext example - Part 3
PowerShell WPF XAML multibinding datacontext template example - Part 4

Continuing from my earlier article series I configured either data context or control to another control with single data binding. In the this exercise I am using multi binding to a control from multiple control and ItemsControl with datacontext. 

In below example I have created datacontext, which I am using on ItemsControl, this datacontext properties will be used next in bindings. I am using multibinding section to merge different values in one control. To make binding understand more effectively I have highlighted values and items with same respected colors.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
$xaml = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="MainWindow"
        Title="DataTemplate example - vCloud-lab.com" Height="350" Width="400">

<Grid Margin="10">
    <TextBlock Text="    Drive     ||     UsedSpace Percent     ||         TotalSpace GB" />
    <ItemsControl ItemsSource="{Binding MyLogicalDiskListProperty}" Margin="20">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid Margin="5">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="30" />
                        <ColumnDefinition Width="150" />
                        <ColumnDefinition Width="50" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="{Binding DriveName}" />
                    <ProgressBar Name="ProgressBarUsedValue" Grid.Column="1" Minimum="0" Maximum="100" Value="{Binding UsedPercentage}"/>
                    <!-- <TextBlock Text=" Grid.Column="2" Minimum="0" {Binding ElementName=ProgressBarElement, Path=Value, StringFormat={}{0:0}%}" HorizontalAlignment="Center" VerticalAlignment="Center" /> -->
                    <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="1">
                        <TextBlock.Text>
                            <MultiBinding StringFormat="{}Used: {0}%/ Total: {1}GB">
                                <Binding Path="Value" ElementName="ProgressBarUsedValue" />
                                <Binding Path="Text" ElementName="TexBoxTotalSize" />
                            </MultiBinding>
                        </TextBlock.Text>
                    </TextBlock>
                    <TextBlock Name="TexBoxTotalSize" Grid.Column="3" Text="{Binding Size}" Margin="5,0"/>
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

</Grid>
</Window>
"@

[void][System.Reflection.Assembly]::LoadWithPartialName('PresentationFramework')

#Read XAML
$window = [Windows.Markup.XamlReader]::Parse($xaml)

$logicalDiskData = Get-CimInstance -Query "Select * from Win32_LogicalDisk" 

#[System.Collections.ArrayList]$logicalDisksInfo = @()
#$logicalDisksInfo = New-Object -TypeName 'System.Collections.ArrayList'
$logicalDisksInfo = [System.Collections.ArrayList]::new()

foreach ($drive in $logicalDiskData)
{
    $size = $drive.Size / 1gb
    $freeSpace = $drive.FreeSpace / 1gb
    $usedSpace = $size - $freeSpace
    $usedPercent = ($usedSpace / $size) * 100
    
    $logicalDisks = New-Object psobject
    Add-Member -InputObject $logicalDisks -Name DriveName -MemberType NoteProperty -Value $drive.DeviceID
    #$logicalDisks | Add-Member -Name DriveName -MemberType NoteProperty -Value $drive.VolumeName
    $logicalDisks | Add-Member -Name UsedPercentage -MemberType NoteProperty -Value ([System.Math]::Round($usedPercent))
    $logicalDisks | Add-Member -Name Size -MemberType NoteProperty -Value ([System.Math]::Round($size))
    Add-Member -InputObject $logicalDisks -Name usedSpace -MemberType NoteProperty -Value ([System.Math]::Round($usedSpace))
    $logicalDisks | Add-Member -Name FreeSpace -MemberType NoteProperty -Value ([System.Math]::Round($freeSpace))
    [void]$logicalDisksInfo.add($logicalDisks)
}

$myViewModel = New-Object PSObject -Property @{
    MyLogicalDiskListProperty = $logicalDisksInfo
}

$window.DataContext = $myViewModel

$window.ShowDialog()

Below is the result screenshot of the PowerShell WPF GUI. Data is taken from data context and same data is used and manipulated inside XAML.

Microsoft PowerShell WPF XAML multibinding data binding data context data template examples textblock textbox wmi object ciminstance win32_logicaldisk cim wmiobject progressbar textbox.png

If you are planning to use the data from json your json data will look like below, which you can convert to PowerShell Object using ConvertFrom-Json cmdlet and use as datacontext.

{
    "MyLogicalDiskListProperty": [
      {
        "DriveName": "C:",
        "UsedPercentage": "56",
       "Size": "247"
      },
      {
        "DriveName": "D:",
         "UsedPercentage": "66",
         "Size": "217"
      }
   ]
}

Download this script here Powershell_WPF_DataContext_DataTemplate.ps1 here or this script is also available on github.com/janviudapi.

Useful Articles
Executing PowerShell script from PHP HTML web server
Send system disk space utilization HTML report Email using PowerShell
Send Email using PowerShell with .net object System.Net.Mail.MailMessage
PowerShell XML OperationStopped: No coercion operator is defined between types 'System.Object&' and 'System.Object'
Powershell Create new file if not exist, if exist Rename file
PowerShell Create XML document with XmlWriter .net object
PowerShell save export data to XML file
Resolved PowerShell Visual studio code stuck with 'Starting up PowerShell' in status bar
Building basic simple Web Server using PowerShell
Running Your First PowerShell Scripts With Jenkins and Git
Git clone or push Missing or invalid credentials fatal authentication failed
PowerShell How to find file and folders in Azure Storage Account Blobs and Containers
PowerShell GUI get patch updates information with disk space and uptime

Go Back

Comment

Blog Search

Page Views

11497474

Follow me on Blogarama