Button Visibility in WPF at startup

1.7k views Asked by At

I have some button that I want them to be hidden when the wpf loads up. I use this:

public MainWindow()
    {
        mySendButton.Visibility = Visibility.Hidden;
        myReceiveButton.Visibility = Visibility.Hidden;                                                
        InitializeComponent();
    }

But the above generating an error. i think I wrote them not at the right place. Can I get a help please?

2

There are 2 answers

0
Nikhil Agrawal On BEST ANSWER

InitializeComponent Method initializes the components, in your case buttons. Your buttons before InitializeComponent call is null because they are not initialized and setting its visibility throws the exception.

That's why in some languages it is written

//Add any code after the InitializeComponent() call.

You need to do

public MainWindow()
{
    InitializeComponent();
    mySendButton.Visibility = Visibility.Hidden;
    myReceiveButton.Visibility = Visibility.Hidden;                        
}

BTW, you can set the visibility in XAML like this.

<Button name="mySendButton" Content"Send" Visibiity="Collapsed" />
0
Marco Rebsamen On

The problem is, you are trying to access the button before it is initialized. This happens in the InitializeComponent() method. Either place the lines below that method:

public MainWindow()
{                                                
    InitializeComponent();
    mySendButton.Visibility = Visibility.Hidden;
    myReceiveButton.Visibility = Visibility.Hidden;
}

or just use the appropriate property in the visual designer.