2012-04-25 142 views
1

嗯,我似乎有一個問題,我的主窗口上我試圖做到這一點:對象引用需要非靜態字段,方法或屬性

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); // 
    } 

我的其他窗口,我有這樣的:

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

但我得到的錯誤:

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

有誰知道我怎麼能解決這個問題?它適用於我的用戶控件,但不適用於其他窗口?

我的主窗口實際上被命名爲MainWindow,所以我可能會有這個困惑。

+2

想想這個:*哪個* MainWindow'做y你想改變'StudentID'嗎? – 2012-04-25 15:10:04

+2

@JonSkeet。 *主要*當然。 :) – aquinas 2012-04-25 15:10:57

+1

ahhh謝謝!這確實有道理! – 2012-04-25 15:12:45

回答

5

您需要設置您的MainWindow類的實例StudentID。嘗試

((MainWindow)Application.Current.MainWindow).StudentID = (String)((Button)sender).Tag; 
1

因爲MainWindow是您的班級的名稱,而不是MainWindow的一個實例。你需要像這樣的東西:

MainWindow mw = new MainWindow(); 
mw.StudentID = (String)((Button)sender).Tag; 
+1

除了創建一個新的MainWindow實例幾乎可以肯定*不是正確的做法。 OP想要獲得對*現有* MainWindow的引用的可能性更大。 – 2012-04-25 15:11:22

+0

我還有另一個問題與此相關(OnStudentIDChanged),我認爲它更多是我命名主窗口MainWindow的錯。 – 2012-04-25 15:16:26

+0

絕對如此。我試圖將OP指向它指向* class * MainWindow的事實,它可能是一個錯字(可能它們的意思是:mainWindow而不是MainWindow,或MyApplication.MainWindow)等等。 – aquinas 2012-04-25 15:17:18

0

我試圖通過編寫以下從UserControl更新的MainWindow一個TextBox並獲得

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

'WpfApplication1.MainWindow.textBox1' 

我解決了這個錯誤此錯誤:

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

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

這是由Rytis I建議