how to hide or show image with just one button click event
10,262
The Button
control has no notion of when it has been clicked. Instead of using a regular Button
, it would make more sense for you to use a ToggleButton
, which does know when it has been clicked. The ToggleButton
class has an IsChecked
property that will be set to true
after the first click and back to false
after another click. Therefore there is a very simple solution using this ToggleButton
property:
image.Visibility = toggleButton.IsChecked ? Visiblity.Visible : Visiblity.Collapsed;
Author by
Marss
Updated on June 04, 2022Comments
-
Marss almost 2 years
I am adding the button and image element using code. My wpf application is able to display an image stored on my project when I click the button. I want to hide the displayed image if I clicked the button again. How will I be able to achieve this if I only have one event handler for my button?
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); grid_parent.RowDefinitions.Add(new RowDefinition { Height = new GridLength(150, GridUnitType.Pixel) }); grid_parent.RowDefinitions.Add(new RowDefinition { Height = new GridLength(150, GridUnitType.Auto)}); Button btn_submit = new Button { Content = "Submit" }; btn_submit.HorizontalAlignment = System.Windows.HorizontalAlignment.Center; Grid.SetRow(btn_submit, 1); btn_submit.Click += btn_submit_Click; grid_parent.Children.Add(btn_submit); } void btn_submit_Click(object sender, RoutedEventArgs e) { image = new Image { Source = new BitmapImage(new Uri(@"/AddControlsThroughClass;component/images/julie.jpg", UriKind.Relative)) }; image.Stretch = Stretch.Uniform; Grid.SetRow(image, 0); grid_parent.Children.Add(image); } }
-
Sheridan over 10 years-1 This is WPF, not Winforms... look at the question tags. you do not set
Visibilty
like that in WPF.