Binding a GroupBox's IsEnabled to a CheckBox's IsChecked

Sep 19, 2011 at 2:22 PM

I am trying to bind a groupbox's IsEnabled property to a CheckBox's IsChecked property. The following XAML is what I am trying to achieve:

<GroupBox Name="Group1" Header="Group 1" IsEnabled="{Binding ElementName=Check1, Path=IsChecked}" />
Currently, I am using the On_Checked and On_Unchecked event handlers for the CheckBox as follows:
Window -SizeToContent WidthAndHeight {
    Grid -Columns 1 -Rows 2 {
        CheckBox -Name Check1 'Enable Group 1' -On_Checked {
            $Group1.IsEnabled = $true
        } -On_Unchecked {
            $Group1.IsEnabled = $false
        }
    
        GroupBox -Name Group1 -Row 1 'Group 1' {
            TextBox 'Item 1'
        }
    }
} -On_Loaded {
    $Group1.IsEnabled = $false
    #$Group1.SetBinding([System.Windows.Controls.Control]::IsEnabledProperty, (Binding -ElementName Check1 -Path IsChecked))
} -Show

Is there a better/proper way to do this binding? I tried manually adding the binding in the On_Loaded event handler, which works just fine in the code behind of an actual WPF app, but it had no effect when running the script above with the SetBinding call uncommented and the Checked/Unchecked event handlers removed.

Coordinator
Oct 16, 2011 at 8:30 PM

If I recall correctly, you can't use element name because we build the whole UI in code rather than in XAML ... but regardless, you CAN do it without handling events, you just have to specify the -Source parameter instead of the -ElementName:

Window -SizeToContent WidthAndHeight {
    Grid -Columns 1 -Rows 2 {
        CheckBox -Name Check1 'Enable Group 1'
        G roupBox -Name Group1 -Row 1 'Group 1' {
            TextBox 'Item 1'
        } -IsEnabled:$false
    }
} -Show -On_Loaded {
 $Group1.SetBinding( [System.Windows.Controls.Control]::IsEnabledProperty, (New-Binding -Source $Check1 -Path IsChecked)) }

Or you can use Set-Property:

 

New-Window -SizeToContent WidthAndHeight {
    New-Grid -Columns 1 -Rows 2 {
        New-CheckBox -Name Check1 'Enable Group 1'
        New-GroupBox -Name Group1 -Row 1 'Group 1' {
            New-TextBox 'Item 1'
        } -IsEnabled:$false
        #(New-Binding -Path IsChecked -ElementName Check1)
    }
} -On_Loaded {
   Set-Property -InputObject $Group1 @{IsEnabled = {New-Binding -Source $Check1 -Path IsChecked}}
} -Show

 

 

I actually expected that you could write: -IsEnabled { New-Binding ... } on the GroupBox parameter, but because we convert booleans into switch parameters,  it doesn't work.  Of course, even if it did work, you couldn't necessarily say $Check1 in there, because it wouldn't necessarily be defined yet, so doing it in On_Loaded is probably the only option for this scenario.