非静态字段、方法或属性需要对象引用
本文关键字:属性 对象引用 方法 静态 字段 | 更新日期: 2023-09-27 18:32:24
嗯,我似乎有一个问题,在我的主窗口中,我正在尝试这样做:
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 类的实例上设置 StudentID。
((MainWindow)Application.Current.MainWindow).StudentID = (String)((Button)sender).Tag;
因为MainWindow
是类的名称,而不是 MainWindow 的实例。你需要这样的东西:
MainWindow mw = new MainWindow();
mw.StudentID = (String)((Button)sender).Tag;
我试图从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!
这是里蒂斯一世建议的