开发者

Setting combobox default value using SelectedIndex

开发者 https://www.devze.com 2023-04-02 07:13 出处:网络
Why is that whenever I try to put SlectedIndex to 0, it always remains -1 ? public partial class Window1 : Window

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.SelectedInde开发者_运维知识库x = 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 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.


Try this instead of setting the index.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号