Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
630 views
in Technique[技术] by (71.8m points)

c# - How do I make a textbox visible and hidden with a checkbox?

So I am trying to make my textbox invisible when a checkbox is not checked. Everything works fine untill I check the box and then uncheck it again. The textbox will stay visible.

private void chbon_Checked_1(object sender, RoutedEventArgs e)
    {
        if (cchbon.IsChecked == true)
        {

            txtshow.Visibility = System.Windows.Visibility.Visible;
        }
        if (chbon.IsChecked == false)
        {
            txtshow.Visibility = System.Windows.Visibility.Hidden;
        }
    }

This is the XAML for the Checkbox:

<CheckBox x:Name="chbon" Content="On" HorizontalAlignment="Left" Margin="175,84,0,0" VerticalAlignment="Top" Checked="chbon_Checked_1"/>
<TextBox x:Name="txtshow" HorizontalAlignment="Left" Height="23" Margin="272,82,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="29" Visibility="Hidden"/>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The event Checked does not fire when uncheck happens. The event Unchecked is for that purpose.

... Checked="chbon_Checked" Unchecked="chbon_Unchecked"/>

and no need to monitor cchbon.IsChecked in code behind:

private void chbon_Checked(object sender, RoutedEventArgs e)
{
        txtshow.Visibility = System.Windows.Visibility.Visible;
}
private void chbon_Unchecked(object sender, RoutedEventArgs e)
{
        txtshow.Visibility = System.Windows.Visibility.Hidden;
}

Alternatively, you can do it via binding and a converter:

<Window.Resources>
    <BooleanToVisibilityConverter x:Key="BoolToVis"/>
</Window.Resources>

...

<CheckBox x:Name="chbon"/>
<TextBox x:Name="txtshow" Visibility="{Binding ElementName=chbon, Path=IsChecked, 
         Converter={StaticResource BoolToVis}, FallbackValue=Hidden}"/>

Note that, Once you managed this approach you may want to implement a custom converter since the built-in BooleanToVisibilityConverter returns Visible/Collapsed for True/False input (and not Visible/Hidden)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...