Partial
Partial

Reputation: 9989

WPF/Forms: Creating a new control programmatically that can have events

I wanted to know if it was possible to create a control from another control and which this new control could process certain events.

For example, lets say we have a Button that once it is clicked on will create a ComboBox. Could this new ComboBox be capable of processing a certain event such as a SelectionChanged event?

Upvotes: 1

Views: 2099

Answers (1)

Charlie
Charlie

Reputation: 15247

Sure thing. Simply provide an event handler and hook it up to the event:

public Window1()
{
    InitializeComponent();

    Button button = new Button();
    button.Click += new RoutedEventHandler(button_Click);
}

void button_Click(object sender, RoutedEventArgs e)
{
    ComboBox combo = new ComboBox();
    combo.SelectionChanged += new SelectionChangedEventHandler(combo_SelectionChanged);
}

void combo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // Do your work here.
}

Upvotes: 3

Related Questions