简体   繁体   中英

WPF Fire event for dynamically added control in stack panel

I am adding adding a radio button to stack panel for each item in List and that happens without issue. (it adds 4 or 6 radio buttons as those would be count of items in my list).

foreach (var nearestgage in nearestgages)
{
     StackPanel.Children.Add(new RadioButton { Content = nearestgage.GageSize.ToString(), Margin = new Thickness(1, 1, 1, 1) });                        
}

Now what i want to do is when any of these dynamically created radio buttons are selected at run time. I want to fire a event. So what i am thinking is i will have to attach a handler to my radio button click . I tried a few methods but not able to that. I have another radio button in the grid which does not belong to this group as well. Please suggest what would be the ideal way to do this.

Here's a little sample, adding the event to the radio button when it's generated.

XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        Loaded="Window_Loaded">
    <StackPanel Name="StackPanel">

    </StackPanel>
</Window>

C#

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        for (int i = 1; i <= 10; i++)
        {
            RadioButton rb = new RadioButton();
            rb.Content = "Item " + i.ToString();
            rb.Click += rb_Click;
            StackPanel.Children.Add(rb);
        }
    }

    void rb_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show((sender as RadioButton).Content.ToString());
    }
}

To deal with keeping the radio button actions separate, set the group name:

rb.GroupName = "Dynamic";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM