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.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;
精彩评论