Sometimes you need to enable / disable all the controls that are inside a StackPanel or a Grid depending on some conditions… well it seems something pretty straight forward until you realize that these elements does not have available the IsEnabled property … ouch! What to do? Well… going control by control setting the IsEnabled property is a pain in the neck, encapsulating that elements in an user control can be an elegant solution but doesn’t fit to all scenarios (maybe is just a simple layout, or you don’t have the time to make all that refactoring). Is there any easier solution?...
Let’s check how it works with a simple sample: We have the following layout / XAML:
<StackPanel Orientation="Vertical" HorizontalAlignment="Center" Margin="5">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70"/>
<ColumnDefinition Width="90"/>
</Grid.ColumnDefinitions>
<TextBlock Text="Fullname" Grid.Row="0" Grid.Column="0" />
<TextBox Grid.Row="0" Grid.Column="1"/>
<TextBlock Text="Address" Grid.Row="1" Grid.Column="0"/>
<TextBox Grid.Row="1" Grid.Column="1"/>
</Grid>
<Button Content="Update" Margin="5" Width="100"/>
</StackPanel>
Let’s Wrap the stack panel with the content template and set it’s IsEnabled property to false, gotcha !! we get the desired behavior with just two lines of code :).
<ContentControl IsEnabled="false">
<StackPanel Orientation="Vertical" HorizontalAlignment="Center" Margin="5">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70"/>
<ColumnDefinition Width="90"/>
</Grid.ColumnDefinitions>
<TextBlock Text="Fullname" Grid.Row="0" Grid.Column="0" />
<TextBox Grid.Row="0" Grid.Column="1"/>
<TextBlock Text="Address" Grid.Row="1" Grid.Column="0"/>
<TextBox Grid.Row="1" Grid.Column="1"/>
</Grid>
<Button Content="Update" Margin="5" Width="100"/>
</StackPanel>
</ContentControl>