Thursday, October 8, 2015

WPF: Programmatically Add Click Event to a Button.


Sometime we create button on the fly and want to attach an event at runtime. 
so here we go. 

// Creating button on the fly.
 Button btn = new Button();
 // Passing an argument to the handler
 btn.CommandParameter= "0012" ;

// attaching handler to click event.
btn.Click += teamHandler;


// Handler for button
 protected void teamHandler(object sender, RoutedEventArgs args) {
            var btn = (Button)sender;
            int teamId = int.Parse(btn.CommandParameter.ToString());
            string name = Repository.GetItem(teamId).Name
            MessageBox.Show(name);
}

No comments:

Post a Comment