Mr. Blond
Mr. Blond

Reputation: 1167

When opening same window multiple times and use current window instance, throws null reference exception

     When i open the same window multiple times, the last one becomes as 'Current.MainWindow' and for other windows this 'Current' instance is null. Ofcourse when I'm trying to instantiate it, it throws null reference exception. On each window i have button which will hide/show all controls inside that window + change it's opacity. Maybe there is another way to do that, or rather than using Current.MainWindow instance use something else?

Method that wil change window opacity:

private void btnHideShow_Click(object sender, RoutedEventArgs e)
{
    if (this._hide)
    {
        Application.Current.MainWindow.Background.Opacity = 0;
        this._hide = false;
        //...
    }
    else 
    {
        Application.Current.MainWindow.Background.Opacity = 0.1;
        this._hide = true;
        //...
    }
}

Upvotes: 0

Views: 106

Answers (1)

Raúl Otaño
Raúl Otaño

Reputation: 4760

If that code is the code behind of the window, you simply can do:

private void btnHideShow_Click(object sender, RoutedEventArgs e)
{
    if (this._hide)
    {
        this.Background.Opacity = 0;
        this._hide = false;
        //...
    }
    else 
    {
        this.Background.Opacity = 0.1;
        this._hide = true;
        //...
    }
}

Also you may give name to your controls with the x:Name attr:

<Grid x:Name="LayoutRoot"></Grid>

Then you can use it in the code behind.

Upvotes: 1

Related Questions