What I'm Doing Wrong

Jun 24, 2013 at 10:36 AM
Hello, I have an Issue, and I don't understand what i'm doing wrong :
I'll make an really simple example :
Import-Module ShowUI

New-StackPanel -Name Test {
    New-TextBlock -Name TextTest "essai"
    $TextTest.Foreground = 'Red'
} -Show
I don't understand Why $TextTest.Foreground = 'Red' don't work.
How I can do this kind of modification ( the goal is to change an attribute later in my code)
Jun 24, 2013 at 5:46 PM
Ah... that's the weakness of our variable trick.

First: The automatic variables (where the $TestText variable is generated for you based on the -Name you gave to a TextBlock) only exist in event handlers.
Second: The automatic variables don't exist until after the control is added to the actual control hierarchy, so even if you were in an event handler, if you make a new control like that and want to refer to it again within the same scriptblock you should assign it to a variable, and then output the variable.
New-StackPanel -Name Test {
    $TextTest = New-TextBlock -Name TextTest "essai"
    $TextTest.Foreground = 'Red'
} -Show