C# WPF Application Hiding button on click

7.5k Views Asked by At

I have been asked to create a C# WPF application in VS 2013 and scenario is as under. At the start of the application, a form must appear with two buttons on it. On the top button, the text “Button 1” must be written and on the bottom button the text “Button 2” must be written. For the first time, when any of the button 1 or button 2 is clicked then it will disappear and the other button will stay unchanged. For example, user clicks button 1 for the first time then button 1 will disappear. Button 2 will be unchanged. Now there is only one button on the window that is button 2. On clicking button 2 it will disappear and button 1 will reappear on the window. Now if the user clicks button 1 then it will disappear again and button 2 will reappear. This process may go on indefinitely until the application is terminated by clicking the close button.

I have created all the things but button1.Visible=true; cannot be entered VS is generating warnings that" sytem.windows.control.button does not contains a defination for Visible.

I need help please

2

There are 2 best solutions below

4
On

In WPF we have Control.Visibility which needs to be set as Visibility.Visible or as required.

So you need to do it like this to hide:

button1.Visibility=Visibility.Collapsed
0
On

Under the Button Click Method you want this:

private void button1_Click(object sender, RoutedEventArgs e)
{
    //Hides Current Button
    button1.Visibility = Visibility.Collapsed;

    //Checks and Shows Button 2
    if (button2.Visibility == Visibility.Collapsed)
    {
        button2.Visibility = Visibility.Visible;
    }
}    

private void button2_Click(object sender, RoutedEventArgs e)
{
    //Hides Current Button
    button2.Visibility = Visibility.Collapsed;

    //Checks and Shows Button 1
    if (button1.Visibility == Visibility.Collapsed)
    {
        button1.Visibility = Visibility.Visible;
    }
}

In order to obtain these methods you should declare a Click="" Method in XAML

<Button Name="button1" Click="button1_Click"><Button>
<Button Name="button2" Click="button2_Click"><Button>