Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF, hide textbox when unchecked

I am tryting to hide textbox when checkbox value is true which I've done but when unchecked the textbox doesn't hide what can I do to fix this?

Here is my code

private void textBox4_TextChanged(object sender, TextChangedEventArgs e)
    {
    }

    private void checkBox_Checked(object sender, RoutedEventArgs e)
    {
        Handle(sender as CheckBox);
    }
    private void checkBox_Unchecked(object sender, RoutedEventArgs e)
    {
        Handle(sender as CheckBox);
    }

    void Handle(CheckBox checkBox)
    {
        bool chkd = checkBox.IsChecked.Value;

        if (chkd)
        {
            textBox4.Visibility = Visibility.Visible;
        }
        else
        {
            textBox4.Visibility = Visibility.Hidden;
        }
    }
like image 304
Wigord Avatar asked Mar 12 '26 22:03

Wigord


2 Answers

Just use something like this:

private void checkBox_CheckChanged(object sender, RoutedEventArgs e)
{
    textBox4.Visibility = (checkBox.IsChecked) ? Visibility.Visible : Visibility.Hidden;
}

Add this to the CheckChanged event like this:

checkBox.CheckedChanged += checkBox_CheckChanged;
like image 195
Fᴀʀʜᴀɴ Aɴᴀᴍ Avatar answered Mar 15 '26 13:03

Fᴀʀʜᴀɴ Aɴᴀᴍ


You can try the following solution -> Binding to a WPF ToggleButton's IsChecked state

That solution basically related the check box to the content that it wants to hide on xaml using a converter instead of code behind.

like image 34
aggietech Avatar answered Mar 15 '26 11:03

aggietech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!