PowerShell and WPF: Labels

Continuing on in my series of working with WPF and PowerShell, today’s article is about Labels. While there really isn’t a lot with using labels other than just displaying something in your UI, it is another control in WPF and I want to make sure I show everything no matter what it is. Plus this gives me a change to show another technique that you can do with other controls as well.

A label is a control that can be added to your layout in your UI that can display either text or an image and is a read-only control, meaning that you cannot directly write to it (such as clicking on it and typing away). You can write to it programmatically by performing an action that updates the content property of the label. It is also important to know that labels do not have the ability to wrap text, meaning that if the text in the label is too big, it will keep going beyond the end of the label. To get around this, you can add a TextBlock in the label that supports wrapping.

Lets get started by creating a label and 2 buttons on a canvas.

#Build the GUI
[xml]$xaml = @"
<Window 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="Window" Title="Initial Window" WindowStartupLocation = "CenterScreen"
    Width = "800" Height = "600" ShowInTaskbar = "True" Background = "lightgray">    
        <Canvas x:Name="Canvas">
            <Button x:Name = "Button1" Height = "75" Width = "150" Content = 'Change Label Colors' ToolTip = "Button1"
                Background="Red" Canvas.Left = '150' Canvas.Top = '50'/>
            <Button x:Name = "Button2" Height = "75" Width = "150" Content = 'Rotate Label' ToolTip = "Button2"
                Background="Red" Canvas.Right = '150' Canvas.Top = '50'/>                
            <Label x:Name = "label1" Height = "75" Width = "300" Content = 'Label1' ToolTip = "label1"
                Background="Red" Canvas.Left = '250' Canvas.Bottom = '200'/>                               
        </Canvas>
</Window>
"@
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$Window=[Windows.Markup.XamlReader]::Load( $reader ) 

#Connect to Control
$button1 = $Window.FindName("Button1")
$button2 = $Window.FindName("Button2")
$label1 = $Window.FindName("label1")
$Canvas = $Window.FindName("Canvas")

$Window.ShowDialog() | Out-Null

image

As with the button and other controls, we can change the fonts to make it look better or to fit whatever the requirement is.

$label1.FontSize = "12"
$label1.FontWeight = "Bold"
$label1.FontFamily = "Times New Roman"

image

Centering the text in a label is a breeze with the HorizontalContentAlignment and VerticalContentAlignment property used either in the XAML code or set using the example below:

$label1.HorizontalContentAlignment = 'Center'
$label1.VerticalContentAlignment = 'Center'

image

Putting an image on is just like what we did with the buttons:

[xml]$xaml = @"
<Window 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="Window" Title="Initial Window" WindowStartupLocation = "CenterScreen"
    Width = "800" Height = "600" ShowInTaskbar = "True" Background = "lightgray">    
        <Canvas x:Name="Canvas">
            <Button x:Name = "Button1" Height = "75" Width = "150" Content = 'Change Label Colors' ToolTip = "Button1"
                Background="Red" Canvas.Left = '150' Canvas.Top = '50'/>
            <Button x:Name = "Button2" Height = "75" Width = "150" Content = 'Rotate Label' ToolTip = "Button2"
                Background="Red" Canvas.Right = '150' Canvas.Top = '50'/>                
            <Label x:Name = "label1" Height = "75" Width = "300"  ToolTip = "label1"
                Background="Red" Canvas.Left = '250' Canvas.Bottom = '200' >
                <Image Source="C:\Users\Administrator\Desktop\Avengers.JPG" Stretch="Fill"/>
            </Label>                               
        </Canvas>
</Window>
"@

image

If you look at the two buttons, both of them have a specific action that will happen on the label when pressed. The button on the left will update the label background and foreground color when pressed while the button on the right will actually rotate the label. Because I want to go a little more into rotating the label, we will set up the code for the left button first and check out what it does.

$button1.Add_Click({    
    $backgroundColor = (Get-Random -InputObject @("red","black","blue","yellow","green"))
    $foregroundColor = (Get-Random -InputObject @("red","black","blue","yellow","green"))
    $label1.background = $backgroundColor
    $label1.Foreground = $foregroundColor
    $label1.Content = ("Changed foreground color to {0} `rand background color to {1}" -f $foregroundColor,$backgroundColor)
    $Script:Label = $label1.Content
})

image

One more click…

image

Now that we have done that, it is time to look at rotating a control. Rotating a control isn’t that complicated, but does require you to know the angle of the rotation as well as the coordinate on the control that the UI will rotate on (X and Y coordinates). Once you know these 3 things, it is just a matter of creating a RotateTransform object that can be applied to the control’s RenderTransform property. Note that labels are not the only control that can be rotated!

First lets take a look at the label’s RenderTransform property to see a Before shot.

$label1.RenderTransform

image

Now lets set up the button click event to rotate the label 45º while keeping the center of the rotation on the X:0 and Y:0 coordinates.

$button2.Add_Click({
    $label1.RenderTransform = New-Object System.Windows.Media.RotateTransform -ArgumentList 45,0,0
})

image

As you can see, the label rotated 45º at the X:0 Y:0 coordinate, which happens to be the upper most left part of the control.

Lets move the center of the rotation to the center of the control and show what happens.

$label1.RenderTransform = New-Object System.Windows.Media.RotateTransform -ArgumentList 45,150,37

image

You can definitely see a change in where the rotation took place on the UI with the label. Something important to keep in mind when using this action. And just to finish it out, lets see the rotation start from the far right of the label control.

$label1.RenderTransform = New-Object System.Windows.Media.RotateTransform -ArgumentList 45,300,0

image

Something fun I put together shows both of the buttons in action and gives the rotation more options to make a complete 360º rotation.

Here are a couple of examples of the rotation with the color change.

image

image

<#
Labels do not have the ability to perform a textwrap, so any lines that are bigger than
the label will not be shown. 
#>

Function Set-Rotation {
    [cmdletbinding()]
    Param (
        [object]$Control,
        [int]$Angle = 45,
        [int]$X = 0,
        [int]$Y = 0
    )
    $Control.RenderTransform = New-Object System.Windows.Media.RotateTransform -ArgumentList $Angle,$X,$Y
}

#Build the GUI
[xml]$xaml = @"
<Window 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="Window" Title="Initial Window" WindowStartupLocation = "CenterScreen"
    Width = "800" Height = "600" ShowInTaskbar = "True" Background = "lightgray">    
        <Canvas x:Name="Canvas">
            <Button x:Name = "Button1" Height = "75" Width = "150" Content = 'Change Label Colors' ToolTip = "Button1"
                Background="Red" Canvas.Left = '150' Canvas.Top = '50'/>
            <Button x:Name = "Button2" Height = "75" Width = "150" Content = 'Rotate Label' ToolTip = "Button2"
                Background="Red" Canvas.Right = '150' Canvas.Top = '50'/>                
            <Label x:Name = "label1" Height = "75" Width = "300" Content = 'Label1' ToolTip = "label1"
                Background="Red" Canvas.Left = '250' Canvas.Bottom = '200'/>                               
        </Canvas>
</Window>
"@

$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$Window=[Windows.Markup.XamlReader]::Load( $reader )
$script:i = 1
#Connect to Control
$button1 = $Window.FindName("Button1")
$button2 = $Window.FindName("Button2")
$label1 = $Window.FindName("label1")
$Canvas = $Window.FindName("Canvas")

#You can change the font to any style, similiar to what was done previously with other examples
$label1.FontSize = "12"
$label1.FontWeight = "Bold"
$label1.FontFamily = "Times New Roman"
$Script:Label = $label1.Content

$button1.Add_Click({    
    $backgroundColor = (Get-Random -InputObject @("red","black","blue","yellow","green"))
    $foregroundColor = (Get-Random -InputObject @("red","black","blue","yellow","green"))
    $label1.background = $backgroundColor
    $label1.Foreground = $foregroundColor
    $label1.Content = ("Changed foreground color to {0} `rand background color to {1}" -f $foregroundColor,$backgroundColor)
    $Script:Label = $label1.Content
})
$button2.Add_Click({
    <#
        Define the Rotate object and supply the Angle, X position and Y position to determine how the angle is applied
        The top left of the label is considered X:0 Y:0
    #>
     Switch ($i) {
       0 {Set-Rotation -Control $label1 -Angle 0 -X 150 -Y 37;$label1.Content= ("{0}`r`rRotated 360{1}" -f $Label,[char]176)}
       1 {Set-Rotation -Control $label1 -Angle 45 -X 150 -Y 37;$label1.Content= ("{0}`r`rRotated 45{1}" -f $Label,[char]176)}
       2 {Set-Rotation -Control $label1 -Angle 90 -X 150 -Y 37;$label1.Content= ("{0}`r`rRotated 90{1}" -f $Label,[char]176)}
       3 {Set-Rotation -Control $label1 -Angle 135 -X 150 -Y 37;$label1.Content= ("{0}`r`rRotated 135{1}" -f $Label,[char]176)}       
       4 {Set-Rotation -Control $label1 -Angle 180 -X 150 -Y 37;$label1.Content= ("{0}`r`rRotated 180{1}" -f $Label,[char]176)}  
       5 {Set-Rotation -Control $label1 -Angle 225 -X 150 -Y 37;$label1.Content= ("{0}`r`rRotated 225{1}" -f $Label,[char]176)}
       6 {Set-Rotation -Control $label1 -Angle 270 -X 150 -Y 37;$label1.Content= ("{0}`r`rRotated 270{1}" -f $Label,[char]176)}
       7 {Set-Rotation -Control $label1 -Angle 315 -X 150 -Y 37;$label1.Content= ("{0}`r`rRotated 315{1}" -f $Label,[char]176)}       
    }
    $Script:i++
    If ($i -eq 8) {$Script:i=-1}
})

$Window.ShowDialog() | Out-Null

With that, I have shown a few things that you can do with Labels and some things such as the rotating that can also be applied to other controls as well.

Up next will be StackPanels in my series.

About Boe Prox

Microsoft Cloud and Datacenter MVP working as a SQL DBA.
This entry was posted in powershell, WPF and tagged , , , . Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s