簡體   English   中英

非靜態字段,方法或屬性需要對象引用

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

嗯,我似乎有問題,在我的主窗口上,我試圖這樣做:

    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,所以我可能對此感到困惑。

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

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

因為MainWindow是類的名稱,所以不是MainWindow的實例。 您需要類似:

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

我試圖從UserControl更新MainWindowTextBox並得到錯誤

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建議的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM