Due to differences between naming and enum I cannot simply bind. Thought of the following:
- Use an array of translated values as datasource;
- Databinding the property with format/parse events to convert between enum and displayed values.
Example:
BindingSource bs = new BindingSource();
bs.DataSource = this.testdata;
this.textBox1.DataBindings.Add("Text", this.bs, "CurrentState", true, DataSourceUpdateMode.OnPropertyChanged);
this.textBox1.ReadOnly = true;
this.comboBox1.DataSource = new List<string>() { "Goed", "Slecht", "Lelijk", "-" };
Binding b = new Binding("SelectedValue", this.bs, "CurrentState", true, DataSourceUpdateMode.OnPropertyChanged);
b.Parse += new ConvertEventHandler(TextToState);
b.Format += new ConvertEventHandler(StateToText);
this.comboBox1.DataBindings.Add(b);
[...]
void StateToText(object sender, ConvertEventArgs e)
{
State state = (State)Enum.Parse(typeof(State), e.Value as string);
switch (state)
{
case State.Good:
e.Value = "Goed";
break;
case State.Bad:
e.Value = "Slecht";
break;
case State.Ugly:
e.Value = "Lelijk";
break;
default:
e.Value = "-";
break;
}
}
void TextToState(object sender, ConvertEventArgs e)
{
switch (e.Value as string)
{
case "Goed":
e.Value = State.Good;
break;
case "Slecht":
e.Value = State.Bad;
break;
case "Lelijk":
e.Value = State.Ugly;
break;
default:
e.Value = State.None;
break;
}
}
This is just an example to test the functionality. The textbox is used to verify the value displayed in the combobox is really the value of the databound property.
This code works. However there are two issues I cannot get around:
- The combobox selects the first value in the datasource (not the state of the property) until the selected item is changed one time. Then the binding works fine.
- I cannot close the form.
I do not understand why the binding is failing to update on load. I tried resetting the binding, etc., but nothing works. Also I have no clue as to why the form is prevented from closing.