我的应用程序创建了一个包含 20 个按钮的列表,这些按钮位于 mainpage.xaml:
private List<Button> CreateList()
{
for (int i = 0; i <= 19; i++)
{
string name = string.Format("button{0}", i+1);
Button buttt = new Button();
buttt.Name = name;
buttt.Content = i + 1;
buttt.Height = 72;
buttt.HorizontalAlignment = HorizontalAlignment.Left;
buttt.VerticalAlignment = VerticalAlignment.Top;
buttt.Width = 88;
buttt.Click += new RoutedEventHandler(this.button_Click);
GameGrid.Children.Add(buttt);
myList.Insert(i, buttt);
}
现在,如果我尝试打乱这个列表,它似乎失去了与页面上实际按钮的连接。
private void Shuffle(List<Button> list)
{
//list[1].Content = "DING!";
Random rand = new Random();
int n = list.Count;
while (n > 1)
{
n--;
int k = rand.Next(n + 1);
Button value = list[k];
list[k] = list[n];
list[n] = value;
}
}
请注意,如果我取消注释//list[1].Content = "DING!";
并注释掉此方法的其余部分,则按钮的内容将在屏幕上更改。所以我假设链接在洗牌过程中被破坏了。
所以我的问题是,当我运行此代码时,会显示按钮,但仍按 1 到 20 的顺序排列,而不是像我预期的那样随机洗牌。
谢谢您的帮助!
编辑:这是克里斯建议的完整代码:
private List<Button> CreateList(List<Marginz> myMargin)
{
for (int i = 0; i <= 19; i++)
{
string name = string.Format("button{0}", i+1);
Button buttt = new Button();
buttt.Name = name;
buttt.Content = i + 1;
buttt.Height = 72;
buttt.HorizontalAlignment = HorizontalAlignment.Left;
buttt.VerticalAlignment = VerticalAlignment.Top;
buttt.Width = 88;
buttt.Click += new RoutedEventHandler(this.button_Click);
Thickness myThickness = new Thickness();
myThickness.Left = myMargin[i].left;
myThickness.Top = myMargin[i].top;
myThickness.Right = myMargin[i].right;
myThickness.Bottom = myMargin[1].bottom;
buttt.Margin = myThickness;
//GameGrid.Children.Add(buttt);
myList.Insert(i, buttt);
}
return myList;
}
这就是它的名字:
private void EasyButton_Click(object sender, RoutedEventArgs e)
{
DifficultyCanvas.Visibility = System.Windows.Visibility.Collapsed;
ReadyCanvas.Visibility = System.Windows.Visibility.Visible;
//set difficulty attributes
difficulty = "Easy";
var myMarg = CreateMarginList(marg);
var buttons = CreateList(myMarg);
Shuffle(buttons);
foreach (var button in buttons)
{
GameGrid.Children.Add(button);
}
}
编辑以获得更多解释: 关于边距。我创建了一个名为 Marginz 的类:
public class Marginz
{
public Marginz()
{
//Constructor
}
public int left { get; set; }
public int top { get; set; }
public int right { get; set; }
public int bottom { get; set; }
}
“marg”是这种类型的列表:
List<Marginz> marg = new List<Marginz>(20);
CreateMarginList() 这样做:
public List<Marginz> CreateMarginList(List<Marginz> myMarg)
{
Marginz one = new Marginz();
one.left = 28;
one.top = 186;
one.right = 0;
one.bottom = 0;
myMarg.Insert(0, one);
Marginz two = new Marginz();
two.left = 133;
two.top = 186;
two.right = 0;
two.bottom = 0;
myMarg.Insert(1, two);
等一直到二十。那么return myMarg;
每个 Button 都有一个唯一的边距,将其放置在 Grid 中。