这就是你需要做的事情
将您的问题类别更改为:
public class Questions
{
public string QuestionType { get; set; }
public string QuestionText { get; set; }
public Choice[] Choice { get; set; }
public Choice SelectedChoice { get; set; }
}
这会为其添加一个Choice 对象,允许我们保存用户从组合框中选择的Choice
将您的 AnswerChoice 类更改为:
public class AnswerChoice
{
public string AnswerText { get; set; }
public Questions Question { get; set; }
public override void ToString() {
return AnswerText;
}
}
这只是在 ToString 方法上添加了一个覆盖。这样做是允许我们将实际对象添加到 ComboBox 而不仅仅是 AnswerText。这给了它更多面向对象的方法,并允许我们在问题的SelectedChoice 中保存对该对象的引用。如果我们在没有覆盖 ToString 方法的情况下添加对象,那么组合框将显示类似于System.Namespace.ClassHere.AnswerChoice
的内容
将您的 ComboBoxControl 类更改为:
public partial class ComboBoxControl : UserControl
{
public ComboBoxControl(Questions question)
{
InitializeComponent();
label1.Text = question.QuestionText;
Choice[] choices = question.Choice;
foreach (var ch in choices)
{
comboBox1.Items.Add(ch.AnswerChoice);
if (ch.IsDefault)
{
comboBox1.Text = ch.AnswerChoice;
}
}
// load the saved answer if it exists
if (question.SelectedChoice != null) {
comboBox1.Text = string.Empty // not sure if this is needed or not
comboBox1.SelectedItem = question.SelectedChoice;
}
}
}
这里有两点改变:
- 我们添加实际的
AnswerChoice 对象,而不是添加 ch.AnswerChoice.AnswerText,以便我们保存对实际对象的引用以供以后使用
- 每当加载一个问题时,它都会检查
SelectedChoice 属性是否为空。如果不是,则将该对象(已加载)设置为SelectedItem
在您的 SurveyView 表单中添加此方法:
private void SelectedAnswerChanged(object sender, EventArgs e) {
Questions question = _presenter.GetQuestion(questionNumber);
question.SelectedChoice = (Choice)((ComboBox)sender).SelectedItem;
}
这是我们稍后将绑定到我们创建的 ComboBox 上的 SelectedIndexChanged 事件的方法。这将保存用户选择的选项。
将您的 DisplayQuestion() 方法更改为:
private void DisplayQuestion(int questionNumber)
{
var qNumber = _presenter.GetQuestion(questionNumber);
if (string.Equals(qNumber.QuestionType, "ComboBoxControl"))
{
controlPanel.Controls.Clear();
var comboBox = new ComboBoxControl(qNumber);
comboBox.Dock = DockStyle.Fill;
comboBox.SelectedIndexChanged += SelectedAnswerChanged;
controlPanel.Controls.Add(comboBox);
}
}
这只是将我们刚刚放在 SurveryView 表单中的 SelectedAnswerChanged 方法与我们创建的 ComboBox 上的 SelectedIndexChanged 事件联系起来。