Xaml:
<ComboBox Grid.Row="1"
Name="CmbClasse"
Grid.Column="3"
Margin="5,5,5,5"
ItemsSource="{Binding DataContext.Classeses}"
SelectedValuePath="ClasseId"
DisplayMemberPath="ClasseName"
SelectedValue="{Binding DataContext.CurrentSelectedPersonagem.IdClasse, Mode=TwoWay}"/>
When I open my application, the ComboBox do not have display any default item. But the item list is working, have all the items on it. Please help, if a image is needed just ask. Thanks.
Here is a method I use all the time.
Firstly, your View Model should have two properties, one to represent the collection, and the other to represent the selected item.
public IEnumerable<YourObject> MyObjects { get; private set; }
public YourObject SelectedObject { get; private set; }
Note: It would be a good idea to use an ObservableCollection
for MyObjects
, and also implement INotifyPropertyChanged
. Use this only if you need to create brand new instances of your collection in the View Model.
Your ComboBox
should then bind to these properties, like so:
<ComboBox ItemsSource="{Binding MyObjects}"
SelectedItem="{Binding SelectedObject}"
...
/>
Now, here comes the magic. When you create your collection, simply set the SelectedObject
to be the FirstOrDefault
item in the list.
private void LoadData()
{
//TODO: Load the data into the collection
//Set the first item
this.SelectedObject = MyObjects.FirstOrDefault();
}
This will ensure that the first item is always selected. You do not need to implement INotifyPropertyChanged
on the SelectedObject
property unless you are planning on manually changing the value of this property in your View Model.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.