I am procedurally generating buttons via code-behind and I wanted to add an eventhandler to the click event. I struggled greatly to make this happen and think there should be a better/cleaner/easier way than what I did? Please help!
public class PatientButtonCreator
{
public PatientButtonCreator() { }
public Button CreatePatientButton(PatientFolder.Patient pt, MainWindow mw)
{
Button btn = new Button() { Content = sp };//stackpanel of labels of patient info added to button content
btn.AddHandler(Button.ClickEvent, new RoutedEventHandler(mw.PatientSelectionRoutedEventHandler));
}
}
public MainWindow(Profile profile)
{
//...
public void PatientSelectionRoutedEventHandler(object sender, RoutedEventArgs e)//populated to every patient button
{
//each patient object is made into a button and added to PatientListStackPanel on the mainWindow
PatientListStackPanel = profile.RetrievePatientButtons(this, PatientListStackPanel);
Patient pt = ((((sender as Button).Content as StackPanel).Children[0] as Label).DataContext as Patient);
//the above line is how I finally got access to the patient, but believe this is very ugly. The object hierarchy is Button has content of a stackpanel which has children of labels which have datacontext of specific Patient objects...
SelectPatient(pt);//goal function to execute on button_click event
e.Handled = true;
}
}
public class Profile
{
List<PatientFolder.Patient> patients = new List<PatientFolder.Patient>(); //goal was for patient list to be private to all other objects
public StackPanel RetrievePatientButtons(MainWindow mw, StackPanel ptListSP)
{
//...
ptListSP.Children.Clear();
View.PatientButtonCreator pbc = new View.PatientButtonCreator();
foreach (PatientFolder.Patient pt in patients)
ptListSP.Children.Add(pbc.CreatePatientButton(pt, mw));
return ptListSP;
}
}