将事件添加到按钮单击

时间:2020-05-21 03:34:45

标签: c# wpf routed-events

我正在通过代码隐藏程序生成按钮,我想向click事件添加事件处理程序。我为此付出了巨大的努力,并认为应该有比我做得更好/更清洁/更轻松的方法?请帮忙!

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

1 个答案:

答案 0 :(得分:0)

了解XAML和MVVM模式。但是,如果必须这样做,可以这样:

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

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

只需将事件处理程序添加到Click事件。 您可以在Documentation中阅读有关Button类及其事件的更多信息。