Search code examples
c#wpfbuttonuniformgrid

How to get button name added on UniformGrid runtime?


Get Button name added on UniformGrid during run time.

My code is:

for (int i = 1; i <= no; ++i)
{
    Button button = new Button()
    {
        Content = i,
        Tag = i,
        Background = Brushes.White,
        Height = 30,
        Width = 30,
        Name="A" + i.ToString() 
    };

    string name=button.Name;

    button.Click += new RoutedEventHandler(button_Click);
    this.grid1.Children.Add(button);

    if (name.Equals("A1"))
    {
        button.Background = Brushes.White;                    
    }                   
}

My requirement is to get Button name in other function:

private void Sum()
{
}

Here is my XAML:

<UniformGrid x:Name="grid1" Margin="816,115,96,354" Grid.Column="1" />    

Solution

  • It isn't clear what is the ultimate goal here. But you can loop through all child of UniformGrid which type is Button to get name of each button and take action accordingly :

    foreach (var btn in grid.Children.OfType<Button>())
    {
        var btnName = btn.Name;
        //take action according to button name
    }