0

I have a a window class with a hidden textbox. I am using a constructor with 1 parameter (string). And if that parameter = "a" I want to make the textbox visible.

  public partial class Window1 : Window
{
    public Window1(string x)
    {
        if(x == "a") this.TBOcena.Visibility = System.Windows.Visibility.Visible;
    }
}

but it seems i am doing something wrong because it does not work. I am getting an exception "An unhandled exception of type 'System.NullReferenceException'"

Not sure how to fix it and not even sure what to look for in google : /

Gumek
  • 3
  • 2

2 Answers2

2

All references to named controls in XAML must be done after a call to InitializeComponent(). Whether that's on the constructor or not is up to you

Jcl
  • 27,696
  • 5
  • 61
  • 92
1

You can call directly the InitializeComponent method in that constructor:

public Window1(string x)
{
    InitializeComponent();
    if(x == "a") this.TBOcena.Visibility = System.Windows.Visibility.Visible;
}

or you could create a default constructor and call it:

public Window1()
{
   InitializeComponent();
} 
public Window1(string x):base()
{
    if(x == "a") this.TBOcena.Visibility = System.Windows.Visibility.Visible;
}

The call to InitializeComponent() (which is usually called in the default constructor of at least Window and UserControl) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected). You can find more details of this method in this post:What does InitializeComponent() do, and how does it work in WPF?

Community
  • 1
  • 1
ocuenca
  • 38,548
  • 11
  • 89
  • 102