Home > Net >  C# WPF Want to store data in a class and use it in multiple different classes in different wpf windo
C# WPF Want to store data in a class and use it in multiple different classes in different wpf windo

Time:12-20

I have 3 classes. 1st stores info, 2nd assigns info to 1nd class, 3rd reads the info from the 1st class.

1st Class, not assigned to any WPF window

public class ProfileInfo //Used to store Name and Surname Data
    {
        public string User_Name { get; set; }
        public string User_Surname { get; set; }
    }

2nd Class, located in WPF window 1

public class InsertInfo //Reads data and stores it in Class 1
    {
        ProfileInfo p = new ProfileInfo();
        p.User_Name = "Bob"; //Example value but normally is read from db
        p.User_Surname = "Jhones"; //Example value but normally is read from db
    }

3rd Class, located in WPF window 2

public class ReadInfo //Reads data from Class 1 and displays it using MessageBox.Show
    {
        ProfileInfo p = new ProfileInfo();
        MessageBox.Show(p.User_Name); // I want this to display Bob but it displays an empty value
        MessageBox.Show(p.User_Surname);
    }

I want Class 1 to store the information until i end the program so that i can retrieve the data in multiple classes.

As i understand this doesn't work because in the 3rd Class im calling for a completely different instance of Class 1 that has no data stored in it??? If so how do i make this work?

I have looked all over the internet for a way to share data between classes but everything seems so difficult and not understandable. Im a beginner so please try to explain it in not so technical language if possible.

CodePudding user response:

The problem is that you create an instance of ProfileInfo inside your InsertInfo class but in the 3rd class, ReadInfo, you create another ProfileInfo instance which is by default, empty. I do not know the details of your system but what you could try is make the ProfileInfo field inside your InsertInfo class a static Property and then you could access it from your other classes:

public class InsertInfo
{
    private static ProfileInfo p = new ProfileInfo();
    public static ProfileInfo P { get { return p; } }

    public void AssignProfileInfo(string username, string surname)
    {
        p.User_Name = username;
        p.User_Surname = surname;
    }
}

And then, to access the stored ProfileInfo you could access the static property:

public class ReadInfo
{
    ProfileInfo p = InsertInfo.P;

    public void ShowInfo()
    {
        MessageBox.Show(p.User_Name); 
        MessageBox.Show(p.User_Surname);
    }
}
  • Related