C#WPF ComboBox SelectedIndex更改

时间:2016-12-07 05:03:41

标签: c# wpf

我有一个ComboBox,其中SelectedIndex设置为零。当用户选择新教授并且SelectedIndex发生更改时,如何以编程方式返回ComboBox的SelectedIndex?以下是我目前的代码。

System.Windows.Controls.ComboBox comboBox1 = new System.Windows.Controls.ComboBox();
returnedTable = sqlFunctions.getTable("professor");
comboBox1.Items.Insert(0, "Professor");

for (int i = 0; i < returnedTable.Tables[0].Rows.Count; i++)
{
    comboBox1.Items.Insert(i + 1, returnedTable.Tables[0].Rows[i]["first_name"].ToString() + " " + returnedTable.Tables[0].Rows[i]["last_name"].ToString());
}

comboBox1.SelectedIndex = 0;

// Code to capture newly changed selected index??

1 个答案:

答案 0 :(得分:0)

SelectionChanged是您正在寻找的事件。您可以在此活动中获得comboBox1.SelectedIndex值。

在构造函数中:

public Window1()
{
    InitializeComponent();

    comboBox1.SelectionChanged += new SelectionChangedEventHandler(comboBox1SelectionChanged);
}

现在处理selectionchanged事件,如下所示:

void comboBox1SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var currentSelectedIndex = comboBox1.SelectedIndex;
}