Tuesday, February 17, 2009

Silverlight: grid dinamikus kezelése

Egy egyszerű lottó generátort készítettem, ahol a Grid celláinak, oszlopainak dinamikus létrehozását akartam szemléltetni:



Tábla generálása:
LottoGrid.Children.Clear();
LottoGrid.RowDefinitions.Clear();
LottoGrid.ColumnDefinitions.Clear();
int sor,oszlop;
if (tipus==LottoTipusok.lotto45)
{
sor = 5;
oszlop = 9;
}
else
{
sor = 6;
oszlop = 15;
}
for (int i = 0; i < sor; i++)
{
RowDefinition rf = new RowDefinition();
LottoGrid.RowDefinitions.Add(rf);
}
for (int i = 0; i < oszlop; i++)
{
ColumnDefinition cd = new ColumnDefinition();
LottoGrid.ColumnDefinitions.Add(cd);
}
gombok = new Button[sor * oszlop];
for (int i = 0; i < sor; i++)
{
for (int j = 0; j < oszlop; j++)
{
Button btn = new Button();
int mezo = (i * oszlop) + j + 1;
btn.Content = mezo.ToString();
LottoGrid.Children.Add(btn);
btn.SetValue(Grid.ColumnProperty, j);
btn.SetValue(Grid.RowProperty, i);
gombok[mezo - 1] = btn;
}
}

Majd sorsolás:
Random rnd = new Random();
int sorsol = Talalat();
for (int i = 0; i < gombok.Length; i++)
{
gombok[i].Background = new SolidColorBrush(Colors.White);
gombok[i].BorderThickness = new Thickness(1);
gombok[i].Tag = 0;
}
while (sorsol > 0)
{
int proba = rnd.Next(gombok.Length);
if ((int)gombok[proba].Tag == 0)
{
gombok[proba].Tag = 1;
gombok[proba].Background = new SolidColorBrush(Colors.Red);
gombok[proba].BorderThickness = new Thickness(3);
sorsol--;
}
}

0 Comments:

Post a Comment

<< Home