axcelenator
axcelenator

Reputation: 1527

Button Visibility in WPF at startup

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?

Upvotes: 0

Views: 1707

Answers (2)

Marco Rebsamen
Marco Rebsamen

Reputation: 605

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.

Upvotes: 1

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48558

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" />

Upvotes: 1

Related Questions