Reputation: 8646
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
Upvotes: 2
Views: 555
Reputation: 892
I faced a same issue. Actually checkbox event fire before label control initialize.
So you need to check first control is initialized first, means control not equal to null.
Or you can directly set visibility using binding(need bool to visibility converter) or you can set visibility using data trigger.
<Label x:Name="lblUsername" Content="Username" Margin="21,10,107,68" Visibility="{Binding path=IsChecked, ElementName=ChkShow, Converter={StaticResource converter}}"></Label>
Here is link for bool to visible converter http://wpftutorial.net/ValueConverters.html
Upvotes: 1
Reputation: 157068
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.
Upvotes: 2