如何使同一 Window 中的每个函数都可以使用变量
How do I make Variable available for every function within the same Window
我想知道是否有办法让同一个 WPF 中的每个函数都可以使用一个变量 window。
我有一个自定义列表class;
我需要从列表中取出一项,在 window 上显示它的数据(没问题)。
然后才能做出决定,例如2个按钮:
如果我按下按钮 1:该列表项将被删除。
如果我按下按钮 2:该列表项将继续存在于列表中。
无论我按下按钮 1 还是 2,显示在 window 上的数据应该更改为属于列表中下一项的数据;我应该可以再次选择那个项目。
重复此过程,因为我 运行 没有列表中的项目。
我根本不知道该怎么做,但我只能将列表分配给 Window 代码中确定的按钮或功能,但无法使其可用于window.
中的每个函数
我不确定我是否已经足够清楚,我知道这可能有点令人困惑;我想不出更好的方式来提出问题。
但我想我的意思是,如果有一种方法可以声明一个变量或列表,对整个 Window 代码是全局的,可用于其中的任何函数。
提前致谢;)
您可以在 Form1(或任何您的表单名称)的顶部定义变量 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
}
}
}
我想知道是否有办法让同一个 WPF 中的每个函数都可以使用一个变量 window。
我有一个自定义列表class; 我需要从列表中取出一项,在 window 上显示它的数据(没问题)。
然后才能做出决定,例如2个按钮: 如果我按下按钮 1:该列表项将被删除。 如果我按下按钮 2:该列表项将继续存在于列表中。
无论我按下按钮 1 还是 2,显示在 window 上的数据应该更改为属于列表中下一项的数据;我应该可以再次选择那个项目。
重复此过程,因为我 运行 没有列表中的项目。
我根本不知道该怎么做,但我只能将列表分配给 Window 代码中确定的按钮或功能,但无法使其可用于window.
中的每个函数我不确定我是否已经足够清楚,我知道这可能有点令人困惑;我想不出更好的方式来提出问题。
但我想我的意思是,如果有一种方法可以声明一个变量或列表,对整个 Window 代码是全局的,可用于其中的任何函数。
提前致谢;)
您可以在 Form1(或任何您的表单名称)的顶部定义变量 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
}
}
}