0

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;
    }
}
0

1 Answer 1

0

Read about the XAML and MVVM pattern. But if you must have to do it, you can do it like this:

private void Method()
{
    btn.Click += Btn_Click;
}

private void Btn_Click(object sender, RoutedEventArgs e)
{
    //Do something ...
}

Simply add event handler to Click event. You can read more about Button class and his events in Documentation.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.