Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object reference is required for the non-static field, method, or property

Tags:

c#

linq

wpf

hmm I seem to have a problem, on my main window I am trying to do this:

    public static readonly DependencyProperty StudentIDProperty = DependencyProperty.Register("StudentID", typeof(String), typeof(LoginWindow), new PropertyMetadata(OnStudentIDChanged));

    public string StudentID
    {
        get { return (string)GetValue(StudentIDProperty); }
        set { SetValue(StudentIDProperty, value); }
    }

    static void OnStudentIDChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        (d as LoginWindow).OnStudentIDChanged(e); // 
    }

On my other window I have this:

MainWindow.StudentID = (String)((Button)sender).Tag;

But I get the error:

An object reference is required for the non-static field, method, or property 'WpfApplication4.MainWindow.StudentID.get'

Does anyone know how I can fix this? It works for my user controls but not other windows?

My main window is actually named MainWindow so I may have had this confused.

like image 532
Kirsty White Avatar asked Apr 25 '12 15:04

Kirsty White


3 Answers

You need to set StudentID on an instance of your MainWindow class. Try

((MainWindow)Application.Current.MainWindow).StudentID = (String)((Button)sender).Tag;
like image 104
Rytis I Avatar answered Oct 10 '22 22:10

Rytis I


Because MainWindow is the name of your class, not an instance of MainWindow. You need something like:

MainWindow mw = new MainWindow();
mw.StudentID = (String)((Button)sender).Tag;
like image 2
aquinas Avatar answered Oct 10 '22 23:10

aquinas


I was trying to update a TextBox in the MainWindow from a UserControl and get the error

Error 1: An object reference is required for the non-static field, method, or property 

'WpfApplication1.MainWindow.textBox1'

I resolved this error by writing the following:

//MainWindow.textBox1.Text = ""; //Error 1

((MainWindow)Application.Current.MainWindow).textBox1.Text = "";//This is OK!

This was suggested by Rytis I

like image 2
mitoylas Avatar answered Oct 10 '22 22:10

mitoylas