c# - MVVM light Silverlight multiple Selection list box initial selection on page load -
i using mvvm light , have list box multiple selection. in mainpage.xaml 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 have (i not want use dependency property reason).
mainpage() { listbox1.selectionchanged = new selectionchangedeventhandler(listbox1_selectionchanged); } void listbox1_selectionchanged(object sender, selectionchangedeventargs e) { var listbox = sender listbox; var viewmodel = listbox.datacontext mainviewmodel; viewmodel.selecteditems.clear(); foreach (string item in listbox.selecteditems) viewmodel.selecteditems.add(item); } and works fine , binds mainviewmodel. when page loaded want first item of the collection items selected default. please let me know how implement this
i'd recommend using listbox's loaded event , bind first item in collection:
mainpage() { listbox1.loaded += new routedeventhandler( onlistbox1loaded ); listbox1.selectionchanged += new selectionchangedeventhandler(listbox1_selectionchanged); } private void onlistbox1loaded( object sender, routedeventargs e ) { // make sure selection changed event doesn't fire // when selection changes listbox1.selectionchanged -= mylist_selectionchanged; listbox1.selectedindex = 0; e.handled = true; // re-hook selection changed event. listbox1.selectionchanged += mylist_selectionchanged; } edit
if can not use loaded event, you'll need create property in model hold item want selected , assign property selecteditem property of listbox.
public class mymodel : inotifypropertychanged { private observablecollection<someobject> _items; public observablecollection<someobject> items { { return _items; } set { _items = value; notifypropertychanged( "items" ); } } private someobject _selected; public someobject selected { { return _selected; } set { _selected = value; notifypropertychanged( "selected" ); } } public void somemethodthatpopulatesitems() { // create/populate items collection selected = items[0]; } // implementation of inotifypropertychanged excluded brevity } xaml
<listbox itemssource="{binding path=items}" selecteditem="{binding path=selected}"/> by having property holds selected item, have access in model item whenever selected item changed user.
Comments
Post a Comment