Libereco
Libereco

Reputation: 111

How do I make Variable available for every function within the same Window

I was wondering if there is a way to make a variable available to every function within the same WPF window.

I have a custom List class; I need to take one item of the list, display it's data on the window (No problem with this).

And then be able to make a decision, 2 buttons for example: if I press button 1: That List Item will be deleted. if I press button 2: That List item will keep living in the list.

Wether I press button 1 or 2, the data Displayed on the window should change to the Data belonging to the next item in the list; And I should be able to make a choice again with that item.

Repeating this process since I run out of items in the list.

I simply can't figure out how to do this, but I've only been able to assing the List to a determined button or function within the Window code, but could not make it available for every function within the window.

Im not sure if I've been clear enough, I know it could be a bit confusing; I couldn't come with a better way to put the question.

But I guess what I mean is if there is a way to declare a variable or list, global to the Whole Window code, available to any function within it.

Thanks in advance ;)

Upvotes: 0

Views: 589

Answers (1)

abagshaw
abagshaw

Reputation: 6582

You can define your variables at the top inside your Form1 (or whatever your form is called) class.

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        //This int and List will be accessible from every function within the Form1 class
        int myInt = 1;
        List<string> myList;

        public Form1()
        {
            InitializeComponent();
            myList = new List<string>(); //Lists must be initialized in the constructor as seen here - but defined outside the constructor as seen above
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            myInt = 1; //This function can access the int
            myList.Add("new item"); //This function can access the list
        }

        private void button2_Click(object sender, EventArgs e)
        {
            myInt = 0; //This function can also access the int
            myList.Clear(); //This function can also access the list
        }
    }
}

Upvotes: 1

Related Questions