WPF如何从另一种形式访问类值?

目标:

Using WPF I have created a Class called User.cs

这里是:

class User
{
    public int id;
    public int access;
    public string username;

    public int ID
    {
        get { return id; }
        set { id = value; }
    }

    public int Access
    {
        get { return access; }
        set { access = value; }
    }

    public string Username
    {
        get { return username; }
        set { username = value; }
    }

在我的MainWindow.xaml.cs

我创建一个用户并分配一个值。

User u = new User();

private void Button_Click(object sender, RoutedEventArgs e)
{
  u.id = 1;
  u.access = 2;
  u.username = "User1";
}

From my new xaml form called Dashboard.xaml.cs. How can I access the information saved from MainWindow.xaml.cs ?

我尝试过的

At Dashboard.xaml.cs

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    txt.Content = User.username
}
评论
  • 深蓝Xx
    深蓝Xx 回复

    首先,让我建议您使用MVVM模式,这将使您现在和将来的生活更加轻松。

    现在,对于您的情况,除非有参考,否则您无法直接访问C#中的随机对象(包括表单)。

    the forms usually have a parent/child relationship which you can use to pass information between them. So if you do this in your MainWindow.xaml.cs:

    Dashboard dash = new Dashboard(u);
    dash.Show();
    

    您可以在仪表板表单的构造函数中接收用户对象。可以朝另一个方向行动,并将信息从孩子传递给父母。