我在我的WPF应用程序的MainWindow中实例化一个类,然后将该Object传递给click事件的第二个窗口。但是当我尝试运行Object的方法时,我传递给Window_Loaded方法中的第二个窗口,我得到错误:
当前上下文中不存在名称
object
。
这是我的MainWindow代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
Object objectName;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
objectName = new Object();
objectName.Text = "text";
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
Settings settingsWindow = new Settings(objectName);
settingsWindow.Show();
}
}
和SettingsWindow:
public partial class Settings : Window
{
public Settings(Object object)
{
InitializeComponent();
}
private void SettingsWindow_Loaded(object sender, RoutedEventArgs e)
{
// get text in object
String name = object.Text;
}
}
所以我能够将Object传递给Window但是如何在新窗口Window_Loaded方法中使用它呢?
答案 0 :(得分:3)
您不在“设置”中实例化对象。
使用:
public partial class Settings: Window
{
Object _object;
public Settings(Object object)
{
_object = object
InitializeComponent();
}
private void SettingsWindow_Loaded(object sender, RoutedEventArgs e)
{
// get text in object
String name = _object.Text;
}
还有一些offtopic提示:
答案 1 :(得分:2)
你在一些不同的事情上出错了。首先,您不能使用具有此语法的对象。你只能通过使用反射或将其转换为字典来使用它。所以真的为它做一个课程会更好:
class MyClass{
public string Text;
}
现在在设置窗口中更改此内容:
MyClass objectName;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
objectName = new MyClass();
objectName.Text = "text";
}
,你需要改变的最后一件事是另一种形式:
public partial class Settings: Window
{
MyClass _object;
public Settings(Object object)
{
_object = object
InitializeComponent();
}
private void SettingsWindow_Loaded(object sender, RoutedEventArgs e)
{
// get text in object
var name = _object.Text;
}
}