需要对象引用来访问非静态字段、方法或属性。

7

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

    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”更改“StudentID”? - Jon Skeet
2
@JonSkeet。当然是主要的。 :) - aquinas
3个回答

12
你需要在你的MainWindow类的实例上设置StudentID。尝试使用以下代码:
((MainWindow)Application.Current.MainWindow).StudentID = (String)((Button)sender).Tag;

2
因为MainWindow是你的类名,而不是MainWindow的实例。你需要像这样做:MainWindow mainWindow = new MainWindow();
MainWindow mw = new MainWindow();
mw.StudentID = (String)((Button)sender).Tag;

2
除非只是创建一个新的MainWindow实例,否则几乎肯定不是正确的做法。更有可能的是,OP想要获取对现有MainWindow的引用。 - Jon Skeet
我还有另一个问题需要解决,与此相关(OnStudentIDChanged)。我认为这更多是我的错,因为我将主窗口命名为MainWindow。 - Kirsty White
当然。我试图指出OP指向的是MainWindow,这可能是一个笔误(可能他们想说的是:mainWindow而不是MainWindow,或者MyApplication.MainWindow等)。 - aquinas

2
我试图从一个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提出的建议。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接