Dotnet Dotnet - 1 month ago 18
C# Question

Issue with Visibility setting of a control inside a group box WPF

I have my groupbox defined inside a window as follows

<ScrollViewer>
<Grid Name="gridMain">
<GroupBox x:Name="grp" Header="Group" Margin="0,71,0,0">
<Grid Margin="0,69,0,0" x:Name="gridmain">
<CheckBox x:Name="ChkShow" Content="Hide Controls" IsChecked="True" Checked="ChkShow_Checked" Unchecked="ChkShow_Unchecked" Margin="27,52,76,38"></CheckBox>
<Label x:Name="lblUsername" Content="Username" Margin="21,10,107,68" Visibility="Hidden"></Label>
</Grid>
</GroupBox>
</Grid>
</ScrollViewer>


This is my code to show/hide the control

private void ChkShow_Unchecked(object sender, RoutedEventArgs e)
{
lblUsername.Visibility = Visibility.Hidden;
}

private void ChkShow_Unchecked(object sender, RoutedEventArgs e)
{
lblUsername.Visibility = Visibility.Visible;
}


But I am unable to find the control it is getting as null so how can I over come this issue

Answer

It's all about order.

The CheckBox is created first. The event handlers are attached and the value is set to True. The event handler fires and tries to call the not-yet-created Label. Hence the Label is having the value null.

If you move the label to above the CheckBox it does work. It will also work if you would attach the event handlers later on, for example in the OnLoad method.