2011-05-26 49 views
1

我有代码为列表中的每个对象创建一个按钮。当每个对象被创建时,它被赋予一个对应于行和列的名称(即name = row1col2)。每个按钮都是动态生成的,添加到网格中,然后设置行/列。稍后,我需要收集“选定”按钮数据,以便我可以对它们所代表的数据执行操作。当我尝试从按钮中获取控件数据时,除网格行/列数据外,一切正常。它对网格中所有选定的行和列都保持不变。LayoutGrid SetRow和SetColumn无法按预期工作

创建按钮:

for (int i = 1; i < row.StackCount+1; i++) 
{ 
    //create button for the column 
    stackButton = new Button(); 
    stackButton.Height = ((newRow.Height - 2)); 
    stackButton.Width = ((newRow.Width/row.StackCount) - 2); 
    stackButton.Background = new SolidColorBrush(Colors.White); 

    //add the button border 
    stackButton.BorderBrush = new SolidColorBrush(Colors.Black); 
    stackButton.BorderThickness = new Thickness(1); 
    stackButton.Style = Application.Current.Resources["flatButton"] as Style; 

    //add the button name 
    stackButton.Name = "Row" + row.LineNumber + "Col" + (i - 1).ToString(); 

    //add the event handler to the button 
    stackButton.Click += new RoutedEventHandler(stackButton_Click); 

    //add a new column 
    newRow.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(newRow.Width, GridUnitType.Star) }); 

    //put the button into the grid 
    newRow.Children.Add(stackButton); 
    Grid.SetRow(stackButton, 0); 
    Grid.SetColumn(stackButton, i-1); 
} 

获取按键数据回

g = (Grid)b.Child; 
foreach (Button currentButton in g.Children) 
{ 
    if (((SolidColorBrush)currentButton.Background).Color == Colors.Gray) 
    { 
     //create a stack object 
     buttonData.StartDate = DateTime.Now; 
     buttonData.LotNumber = LotDisplay.Text; 
     buttonData.RoomID = SilverGlobals.CurrentRoom.RoomID; 

     buttonData.RoomCol = Grid.GetColumn(currentButton); 
     buttonData.RoomRow = Grid.GetRow(currentButton); 

     buttonData.TrayCount = int.Parse(currentButton.Content.ToString()); 
     buttonData.Status = 0; 

     //add stack object to list of stack objects 
     stacks.Add(buttonData); 
    } 
} 

我知道这一定是小东西我失踪。任何人有任何想法?

+0

它为每个按钮的行和列返回什么值? – 2011-05-26 15:11:39

+0

Row = 0和Col = 3(有4个按钮正在处理中) – kereberos 2011-05-26 15:25:34

回答

1

虽然在你的代码的第二部分评论说:

//create a stack object 

你实际上并没有创建一个新的堆栈对象,因此它直接覆盖的0123的单个实例每次迭代。最后看到的行和列的值是最后一次迭代的值。

最终结果是stacks是一个对象的所有相同实例的集合,而不是单独实例的集合。

+0

我知道这是为了这个效果。但我不知道我是如何错过的。谢谢! – kereberos 2011-05-26 15:47:01

+0

很高兴我能帮到你。我使用像你这样的例子来证明为什么我不评论我的代码。 :-) – 2011-05-26 15:49:51

0

这仅仅是一个在黑暗中拍摄,但基于this questionthis question,它可能是你需要设置的行和列的属性添加按钮其父之前 - 这样的事情:

//put the button into the grid 
Grid.SetRow(stackButton, 0); 
Grid.SetColumn(stackButton, i-1); 
newRow.Children.Add(stackButton);