2

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);
    }
}
Marss
  • 573
  • 2
  • 7
  • 24

2 Answers2

1

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;
Sheridan
  • 68,826
  • 24
  • 143
  • 183
0

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)

Ismail Gunes
  • 548
  • 1
  • 9
  • 24
  • 3
    -1 This is WPF, not Winforms... look at the question tags. you do *not* set `Visibilty` like that in WPF. – Sheridan Jan 30 '14 at 12:40