简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM