You cannot rely on selected index, nor would you want to. Every entry in a combo has a display text, value and index. The index is useful for interacting with the UI quickly but it is unreliable if the combo changes. The display text is what is shown to the user and may or may not line up with the value. The value is what that particular item represents and is what you should ideally be storing in a variable for later.
Unfortunately how you do that depends on how you populated the combo box to begin with. In most WPF apps we assume you're using the MVVM pattern. But I suspect you aren't doing that here.
Let's assume you have a fixed list of values, maybe colors. You added these using the designer. In that case the Text is the string value shown to the user. SelectedValue
and SelectedItem
are both ComboBoxItem
. ComboBoxItem.Content
gives you the content (which may not be a string).
//When getting selected item the text is the value
var text = cmdb1.SelectedText
lblValue.Content = text;
But if you instead bound the items to the control directly using some data type you defined then SelectedItem
will be of that type instead.
public class MyData
{
public int Id { get; set; }
public string Name { get; set; }
}
//At initialization of window
cmb1.Items.Add(new MyData() { Id = 1, Name = "First" });
cmb1.Items.Add(new MyData() { Id = 2, Name = "Second" });
cmb1.Items.Add(new MyData() { Id = 3, Name = "Third" });
//When getting selected item
var item = cmb1.SelectedItem as MyData;
if (item != null)
{
lblValue.Content = item.Name;
};
It is the item (of your type) that you should be storing off for later. It is unattached to the UI which means the UI can change without causing any issues.
As for storing the result itself for later you can use a field in the same window if you need it to exist for the life of the window. If you need it to exist longer than the window then you have to promote it up to another object that is accessible after the window goes away.