如何访问动态按钮的事件处理程序? Visual Studio 2015 WPF

时间:2016-01-26 11:33:52

标签: c# wpf visual-studio visual-studio-2015

我正在尝试再次学习C#,我想知道实现我需要的结果的方法是什么,这是我的代码,当我点击按钮时它会创建标签和按钮。

    private void button_Copy_Click(object sender, RoutedEventArgs e)
    {
        counter++;

        Label lbl = new Label();
        lbl.Content = counter.ToString();
        lbl.HorizontalAlignment = HorizontalAlignment.Center;
        lbl.VerticalAlignment = VerticalAlignment.Center;
        lbl.FontSize = 50;

        Button bt = new Button();
        bt.Content = "X";
        bt.HorizontalAlignment = HorizontalAlignment.Right;
        bt.VerticalAlignment = VerticalAlignment.Top;

        grid.Children.Add(lbl);
        grid.Children.Add(bt);
    }

但是,由于它是动态创建的,因此我无法确定将click事件放在何处。我想要发生的是当我点击X按钮时,它将删除我点击的特定标签和x按钮。因此,如果我单击主按钮两次,它会在左上角显示一个带有x的1,在左上角显示带有x的2,当我单击2的x时,它将删除带有2和x的标签按钮2。

2 个答案:

答案 0 :(得分:2)

只需在按钮上添加一个事件处理程序:

private void button_Copy_Click(object sender, RoutedEventArgs e)
{
    counter++;

    Label lbl = new Label();
    lbl.Content = counter.ToString();
    lbl.HorizontalAlignment = HorizontalAlignment.Center;
    lbl.VerticalAlignment = VerticalAlignment.Center;
    lbl.FontSize = 50;

    Button bt = new Button();
    bt.Content = "X";
    bt.HorizontalAlignment = HorizontalAlignment.Right;
    bt.VerticalAlignment = VerticalAlignment.Top;

    // add subscriber
    bt.Click += Button_Click;

    grid.Children.Add(lbl);
    grid.Children.Add(bt);
}

// On click event for button
private void Button_Click(object sender, EventArgs e) 
{
    // do whatever when button is clicked

    // this is a reference to the button that was clicked,
    // you can delete it here or do whatever with it
    Button buttonClicked = (Button)sender;
}

现在,当点击按钮时," Button_Click"将被解雇。

答案 1 :(得分:2)

您可以像这样添加一个处理程序<ion-slide-box ng-repeat="q in questions.list track by $index"> <ion-slide class="default box"> <div class="amount">{{ getAmountQuestion(q.guid) }}</div> <div class="question"><h5>{{ q.fields.question }}</h5></div> </ion-slide> </ion-slide-box> $scope.getQuestionAmount = function(id) { QuestionsService.getAllVotesById(id).then(function (data) { console.log(data.count); }); };

Click

但是你真的应该使用ListView和模板,就像slugster建议的那样。