Search code examples
c#xamluwpwindows-iot-core-10

UWP C# How To Handle Event for Dynamically Created Button(s) and Control


in relation to the post UWP C# Add Button Dynamically and Organizing On StackPanel I have additional questions

  1. how do I control these dynamically created button(s)' event? eg. button 1 to turns on LED 1, button 2 to turns on LED 2 etc.
  2. how to selectively remove the button(s) and reorganize the remaining buttons with no empty spaces in between.

Thank you.

Update: I have a routine to add the client with details such as client IP etc. from the client and to add and display them in a scrollviewer. How do i link either the clientname or client ip to the dictionary?

private async void AddClientList()
    {
        await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
        {
            ClientListUserControl clientListControl = new ClientListUserControl(this, new ClientList(clientName, receiveIP, DateTime.Now, receivePort, receiveService, receiveDEV, receiveSTS, receiveACT));
            ClientList_Panel.Children.Add(clientListControl);
            clientListControl.updateDisplay();
        });
    }

Solution

  • You can also use Tag property of Button to pass the parameter. This property is inherited from FrameworkElement, and generally it is used to get or set an arbitrary object value that can be used to store custom information about this object.

    Please refer to following code.

        private void ButtonCreateNewButton_Click(object sender, RoutedEventArgs e)
        {
            Button b = new Button();
            b.Height = 30;
            b.Width = 100;
            b.VerticalAlignment = VerticalAlignment.Top;
            b.HorizontalAlignment = HorizontalAlignment.Left;
            b.Margin = new Thickness(6, 6, 6, 6);
            b.Content = "Button " + buttonCounter;
            b.Tag = "LED-" + buttonCounter;
            b.Click += Button_Click;
    
            ....
    
            buttonCounter++;
        }
    
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;
            var led = btn.Tag;
            //use led_name as a parameter here, according with this variable to turn on the LED
            TurnOnOffLed(led);
        }