Adam Dowding
Adam Dowding

Reputation: 11

C# WPF Class Property resetting to null

I am trying to simply log the user in, save the validated user name to a class called 'User', property called 'Name' using get set accessors.

Using breakpoints i understand that the value is set correctly in the login page but when i open up the Dashboard page - I just want to change the text of a label to say "Welcome, " + User.Name;

However the value is always null when I try to access it, I am out of ideas!

User Class

namespace Thor_Hours_Calculator
{
    public class User

    {
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    }
}

Login Page

string Username = usernameTxt.Text;
user = new User();
user.Name = usernameTxt.Text;

Dashboard

User NewUser = new User();
string username = NewUser.Name;
welcomemsg.Content += username;

Upvotes: 0

Views: 209

Answers (1)

mm8
mm8

Reputation: 169190

You are creating a new instance of NewUser in the dashboard. You can't expect this instance to have a Name set.

You should pass the instance that you create in the login page to the dashboard or save it somewhere where it can be accessed. The other option would be to make the property static:

public static class User
{
    public static string Name { get; set; }
}

Login Page:

User.Name = usernameTxt.Text;

Dashboard:

string username = User.Name;

Upvotes: 3

Related Questions