Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
624 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 Reply

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...