Why is that whenever I try to put SlectedIndex to 0, it always remains -1 ?
public partial class Window1 : Window
{
private ObservableCollection<string> _dropDownValues = new ObservableCollection<string>();
public ObservableCollection<string> DropDownValues
{
get { return _dropDownValues; }
set { _dropDownValues = value; }
}
private string _selectedValue;
public string SelectedValue
{
get { return _selectedValue; }
set { _selectedValue = value; }
}
public Window1()
{
InitializeComponent();
DataContext = this;
DropDownValues.Add("item1");
DropDownValues.Add("item2");
DropDownValues.Add("item3");
DropDownValues.Add("item4");
DropDownValues.Add("item5");
DropDownValues.Add("item6");
if (combotest.SelectedIndex == -1)
{
combotest.SelectedIndex = 0;
}
}
}
<StackPanel HorizontalAlignment="Left" Margin="10">
<ComboBox Name="combotest"
Margin="0 0 0 5"
ItemsSource="{Binding DropDownValues}"
SelectedValue="{Binding SelectedValue}"
Width="150"/>
</StackPanel>
Please correct me if I am wrong, but you havent set the
SelectedValuePathin your XAML. Also once you setSelectedValuePath, you only need to set the defaultSelectedValue(same as the first item’s value property from your items source) and there is no need for yourSelectedIndexcode.Let me know if this helps.