I am using MVVM light and have a list box with multiple selection. In my Mainpage.xaml I have
<ListBox Name="ListBox1" ItemsSource="{Binding Items}" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="Transparent" Margin="15,15,18,0" SelectionMode="Multiple" Height="100" />
In MainPage.xaml.cs I have (I do not want to use dependency property for some reason).
MainPage()
{
ListBox1.SelectionChanged = new SelectionChangedEventHandler(ListBox1_SelectionChanged);
}
void ListBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var listBox = sender as ListBox;
var viewModel = listBox.DataContext as MainViewModel;
viewModel.SelectedItems.Clear();
foreach (string item in listBox.SelectedItems)
viewModel.SelectedItems.Add(item);
}
and this works fine and binds to my MainViewModel. But When the page is loaded I want the first item of the the collection items to be selected by default. Please let me know how to implement this
I’d recommend using the ListBox’s
Loadedevent and then bind to the first item in the collection:Edit
If you can not use the
Loadedevent, then you’ll need to create another property in your Model that will hold the item you want selected and then assign that property to theSelectedItemproperty of theListBox.XAML
By having another property that holds the currently selected item, you also have access in your Model to that item as well whenever the selected item is changed by the user.