动态单选按钮,如何连接它们以进行事件?

时间:2019-05-08 09:45:35

标签: c# user-interface

我有图片回购,对于每个图片,我都希望在包装面板中有一个单选按钮。我想将所有这些单选按钮连接到一个事件,因此当选中一个按钮时,图片的所有属性都会显示在屏幕上。

问题由于某种原因,我在创建单选按钮的事件成员时无法访问。

我尝试过Google,找不到相同的问题

public void UpdatePictures(PictureRepo pictureRepo)
       {
           foreach (var picture in pictureRepo.RepoCollection)
           {



               WP_mainWrapPanel.Children.Add(new RadioButton
               {

                   Margin = new Thickness(2, 10, 2, 10),
                   Height = 100,
                   HorizontalAlignment = HorizontalAlignment.Center,
                   VerticalAlignment = VerticalAlignment.Top,
                   Content = new Image { Source = new BitmapImage(new Uri(picture.PictureLink, UriKind.Relative)) },
                   Name = picture.Name.ToString(),



           });


           }
       }

单选按钮有一个事件,如果该按钮被选中,由于某种原因我无法访问它。

2 个答案:

答案 0 :(得分:1)

尝试一下:

    private void SetupRadioButton()
    {
        RadioButton radio1 = new RadioButton
        {
            Text = "Your Properties Here",
        };
        radio1.CheckedChanged += Radio1_CheckedChanged;
    }

    private void Radio1_CheckedChanged(object sender, EventArgs e)
    {
        throw new NotImplementedException();
    }

答案 1 :(得分:1)

您需要创建按钮并保留对其的引用。然后您可以添加事件处理程序。

var btn = new RadioButton
{
    Margin = new Thickness(2, 10, 2, 10),
    Height = 100,
    HorizontalAlignment = HorizontalAlignment.Center,
    VerticalAlignment = VerticalAlignment.Top,
    Content = new Image { Source = new BitmapImage(new Uri(picture.PictureLink, UriKind.Relative)) },
    Name = picture.Name.ToString(),
};
WP_mainWrapPanel.Children.Add(btn);
btn.Checked += btn_Checked;

事件定义看起来像这样

private static void btn_Checked(object sender, RoutedEventArgs e)
{
    //do stuff
}