【问题标题】:object reference is required for the non-static field, method, or property非静态字段、方法或属性需要对象引用
【发布时间】:2012-04-25 15:06:43
【问题描述】:

嗯,我似乎有问题,在我的主窗口上我正在尝试这样做:

    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换成什么?
  • @JonSkeet。当然是 main 之一。 :)
  • 啊谢谢!这确实有道理!

标签: c# wpf linq


【解决方案1】:

您需要在 MainWindow 类的实例上设置 StudentID。试试

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

【讨论】:

    【解决方案2】:

    因为MainWindow 是您的类的名称,而不是 MainWindow 的实例。你需要类似的东西:

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

    【讨论】:

    • 除了创建一个新的 MainWindow 实例几乎肯定不是正确的做法。 OP 更有可能希望获得对 existing MainWindow 的引用。
    • 我还有另一个与此相关的问题要解决 (OnStudentIDChanged) 我认为我将主窗口命名为 MainWindow 更多的是我的错。
    • 当然。我试图将 OP 指向他们指向 class MainWindow 的事实,这可能是一个错字(可能他们的意思是:mainWindow 而不是 MainWindow,或 MyApplication.MainWindow)等。
    【解决方案3】:

    我试图从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 建议的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多