Reputation: 347
.xaml
<ComboBox Grid.Row="0" Grid.Column="1" x:Name="cbx_srchResOrg" HorizontalAlignment="Stretch" Style="{DynamicResource ComboBoxStyle}"
ItemsSource="{Binding InfoCombo}" SelectedIndex="0" DisplayMemberPath="Dis_name" SelectedValuePath="Hide_id" SelectedItem="{Binding SelectInfo}"/>
Here is a part of my source code. Why 'SelectedIndex=0' is not working? I want to select [0] value to default at first time, but it just empty box at run time. There are no errors except it. How can I fix it?
Upvotes: 5
Views: 9246
Reputation: 802
You can also use Mode=OneWayToSource
in the SelectedItem
binding with SelectedIndex="0"
.
In your case:
<ComboBox Grid.Row="0"
Grid.Column="1"
x:Name="cbx_srchResOrg"
HorizontalAlignment="Stretch"
Style="{DynamicResource ComboBoxStyle}"
ItemsSource="{Binding InfoCombo}"
SelectedIndex="0"
DisplayMemberPath="Dis_name"
SelectedValuePath="Hide_id"
SelectedItem="{Binding SelectInfo, Mode=OneWayToSource}"/>
Like others said, it binds two way by default, so if the property binded to it (SelectInfo) is null, it will also be set to null.
Upvotes: 3
Reputation: 1315
you have bind SelectedItem
to SelectInfo
, you should set value(in your viewmodel) to SelectInfo
as default, for example
SelectInfo = InfoCombo[0]
or something other whatevere you want to set as default value
Upvotes: 1
Reputation: 2842
As Hej said, you have binded the SelectedItem
with a property in your view model which was null
.
You can fix this by assigning the SelectedItem
in your Viewmodel constructor
Public MyViewModel()
{
SelectInfo = InfoCombo[0];
}
Upvotes: 4
Reputation: 91
Because you are already binding to SelectedItem. It binds two way by default, so if the property binded to it(SelectInfo) is null, it will also be set to null.
Upvotes: 3