Here is the idea:
You can add to your combo box items of any type. How this type is presented in
ComboBox
depends on what its method
object.ToString
returns. You can override this method to return what you need, such as "On"/"Off". Let's take your example.
struct SelectedItemHelper {
internal SelectedItemHelper(bool value, string text) {
Text = text; FValue = value;
}
public override string ToString() {
return Text;
}
internal bool Value {
get { return FValue; }
set { FValue = value; }
}
string Text;
bool FValue;
}
To respond to the change of the item, handle the event
SelectionChanged
:
ComboBox MyComboBox = new ComboBox();
MyComboBox.Items.Add(new SelectedItemHelper(false, "Off"));
MyComboBox.Items.Add(new SelectedItemHelper(true, "On"));
MyComboBox.SelectedItem = 0;
MyComboBox.SelectionChanged += (sender, eventArgs) => {
bool value = ((SelectedItemHelper)((ComboBox)sender).SelectedItem).Value;
ShowPictire(value);
};
This method is very universal and stable: it's easy to support; functionality will not break if you add/delete/modify items (in contrast to case if you access items by index or string). You can add any data to the helper class, whatever you need to support functionality which should respond to item selection. Nearly the same techniques can be used for
ListBox
and
TreeView
.
—SA