vendredi 27 octobre 2017

How to bind multiple elements in PowerShell WPF

I am new to WPF in PowerShell. I am building a small app to perform on demand SQL backups by selecting databases from a form as shown in this capture. WPF PowerShell Form

I have the form working and able to do backups. I am now trying to disable the backup/restore button so that they are only clickable when at least one of the checkboxes has been checked. That requires the binding of backup button to checkboxes (in my understanding). I have been able to find a way to bind it with one checkbox but cannot find a way to do it for multiple checkboxes. My XAML for checkboxes and button is as below.

<CheckBox Name="UAT_DB1" Content="UAT-DB1" HorizontalAlignment="Left" Margin="21,113,0,0" VerticalAlignment="Top" Cursor=""/>
<CheckBox Name="UAT_DB2" Content="UAT-DB2" HorizontalAlignment="Left" Margin="21,140,0,0" VerticalAlignment="Top"/>
<Button Name="btn_backup" Content="Backup" HorizontalAlignment="Left" Height="29" Margin="238,343,0,0" VerticalAlignment="Top" Width="78" IsEnabled="{Binding ElementName=UAT_DB1, Path=IsChecked}"/>

If I select DB1, the button is enabled and on click, checks what has been selected from all the checkboxes and backs up all those databases. Below is the code for click function on backup button.

$WPFbtn_backup.Add_Click(
{ 
    foreach($var in $vars)
    {
        if($var.Name -match "WPFUAT" -and $var.Value.IsChecked -eq $true)
        {
            $name = $var.Value.Content
            $dbs = $dbs + $name
        }        
    }
    if ($dbs.Length -gt 0)
    {
        $msg = $dbs -join "`n"       
        $confirmation = [System.Windows.MessageBox]::Show("Following DBs will be backed up.`n`n$msg",'Tipper','OKCancel','Info')
    }
    else
    {
        [System.Windows.MessageBox]::Show("`nYou have to select a DB to backup or restore.",'Tipper','OK','Warning')
    }        
    switch($confirmation)
    {
        'OK'{
            Backup-Database($dbs)
        }
        'Cancel'{
            Write-Host "You clicked No"
        }
    }       
}

)

Above code calls in a function to backup the DB. This function is as below.

function Backup-Database ($dbnames) 
{    
    foreach( $db in $dbnames )
    {
        Write-Host "[Now backing up $db]"
        Backup-SqlDatabase -Database $db -BackupFile "S:\backup\$db.bak" -ServerInstance localhost
    }
    [System.Windows.MessageBox]::Show("`nDatabase Backup has completed.",'Tipper','OK','Info')    
}

Thanks for reading and your help.




Aucun commentaire:

Enregistrer un commentaire