简体   繁体   中英

Access a list of string from another partial class

I'm trying to access a list of strings in one partial class from another. Trying to access the list from the public partial class MainWindow : Window

`

namespace GymCheckList
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private List<string> data1 = new List<string>();
        public List<string> Data1
        {
            get
            {
                return data1;
            }
        }

`

To call the list I use the following code

namespace GymCheckList
{ 
    public partial class ChooseExercises :  Window
    {

    public List<string> str()
        {
            MainWindow myClass = new MainWindow();
            List<string> calledList = myClass.Data1;
            return calledList;
        }

But when I debug it, I get "Count = 0" for calledList.. Why may it be?

each time str is called it creates a new instance of MainWindow

public List<string> str()
{
    MainWindow myClass = new MainWindow();
    List<string> calledList = myClass.Data1;
    return calledList;
}

that instance doesn't have any data which was entered in a MainWindow which was open at startup (another instance)

try access original instance via Application.Current.MainWindow property

public List<string> str()
{
    MainWindow myClass = (MainWindow)Application.Current.MainWindow;
    return myClass.Data1;
}

this is a quick and dirty fix. preferred approach is to setup properly view models with shared data for each view

Sorry I didn't see this the first time.

private List<string> data1 = new List<string>(); You will always have a new List<string>() with this line.

namespace GymCheckList
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private List<string> data1;
        public List<string> Data1
        {
            get
            {
                if(data! == null) data! = new List<string>();
                return data1;
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM