在我的代码中,我定义了字符串重复编号并将其分配给for循环。但是,当我创建按钮单击事件时,我需要它可访问。不知道怎么做。
有人能给我一些提示吗?
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
string[] assignments = new string[] { "A", "b", "c", "d", "e", "f" };
Random rnd = new Random();
string[] randomingArray = assignments.OrderBy(x => rnd.Next()).ToArray();
string repeatNumber = "";
List<ImageSource> animals = new List<ImageSource>();
for (int i = 1; i < 100; i++)
{
if (i == 9)
{
repeatNumber = randomingArray[i % randomingArray.Length];
animals.Add(new ImageSource() { Source = repeatNumber, Number = i });
}
else if ((i % 9) == 0)
{
animals.Add(new ImageSource() { Source = repeatNumber, Number = i });
}
else
{
animals.Add(new ImageSource() { Source = randomingArray[i % rnd.Next(1,5)], Number = i });
}
ItemsControl1.ItemsSource = animals;
}
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("test");
}
private void btn2_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show((new ImageSource() { Source = repeatNumber })); <-- the name repeatNumber does not exist in current context
}
}
class ImageSource
{
public int Number { get; set; }
public string Source { get; set; }
}
答案 0 :(得分:2)
您需要将repeatnumber
定义为类属性
public partial class MainWindow : Window
{
private string repeatNumber;
public MainWindow()
{
...
否则它仅限于MainWindow
构造函数的范围(&lt; =你想要查看)。