0

I have a dynamically created ComboBox that I need to set the SelectionChanged property for. How can I do this from code?

ComboBox comboBox = new ComboBox()
{
    Background = Brushes.GhostWhite,
    BorderBrush = Brushes.Gainsboro,
    BorderThickness = new Thickness(1),
    Margin = new Thickness(10),
    ItemsSource = new ObservableCollection<string>(list),
    SelectionChanged = "comboBox_SelectionChanged" //SelectionChanged is not a valid property
};
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Scotty
  • 455
  • 7
  • 15
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Apr 04 '15 at 03:27

2 Answers2

2

You would have to attach a SelectionChanged event handler like this:

var comboBox = new ComboBox { ... };
comboBox.SelectionChanged += comboBox_SelectionChanged;

The above assumes that there is a handler method like

private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ...
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
0

SelectionChanged is not a property, it is an event. You are trying to attach event handler to an event using object initializer syntax, and .NET doesn't seems to support that.

Here are some related questions :

Community
  • 1
  • 1
har07
  • 88,338
  • 12
  • 84
  • 137