Adrian
Adrian

Reputation: 20068

Setting combobox default value using SelectedIndex

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>

Upvotes: 0

Views: 13446

Answers (2)

tsells
tsells

Reputation: 2771

Try this instead of setting the index.

string s = DropDownValues[0];
SelectedItem = s;

Upvotes: 1

Vinit Sankhe
Vinit Sankhe

Reputation: 19885

Please correct me if I am wrong, but you havent set the SelectedValuePath in your XAML. Also once you set SelectedValuePath, you only need to set the default SelectedValue (same as the first item's value property from your items source) and there is no need for your SelectedIndex code.

Let me know if this helps.

Upvotes: 2

Related Questions