Reputation: 573
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);
}
}
Upvotes: 2
Views: 11166
Reputation: 69959
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;
Upvotes: 1
Reputation: 558
You can do it by a button however you can do also with keypreview property
Here is a code with keypreview
private void HideShow(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.S)
pictureBox1.Visible = true;
else if (e.KeyCode == Keys.H)
pictureBox1.Visible = false;
}
From the properties of your form add to keydown propery you can hide and show your picture
Or you can do by a button
by this code
pictureBox1.Visible = !pictureBox1.Visible
each time you click the button it will be visible or invisible)
Upvotes: 0