Select first item in Silverlight combobox using MVVM pattern -
this first foray in mvvm , i've encountered following issue:
i've got viewmodel:
public list<workcellgroupinfo> workcellgroupinfocollection { { return _workcellgroupinfocollection; } set { _workcellgroupinfocollection = value; notifypropertychanged( "workcellgroupinfocollection" ); selectedworkcellgroup = _workcellgroupinfocollection.firstordefault(); } } public workcellgroupinfo selectedworkcellgroup { { return _selectedworkcellgroup; } set { _selectedworkcellgroup = value; notifypropertychanged( "selectedworkcellgroup" ); } }
and xaml:
<combobox x:name="workcellgroup" itemssource="{binding workcellgroupinfocollection}" selecteditem="{binding selectedworkcellgroup, mode=twoway}" displaymemberpath="name">
on first load combobox gets populated data can't first item selected. doing wrong?
the workcellgroupinfo derived filterbase class:
public abstract class filterbase { public string id { get; set; } public string name { get; set; } }
you need assign value selectedworkcellgroup
property that.
in viewmodel's constructor, write following code:
if(workcellgroupinfocollection.any()) { selectedworkcellgroup = workcellgroupinfocollection.first(); }
edit:
following works me:
xaml:
<grid x:name="layoutroot" background="white"> <border horizontalalignment="center" verticalalignment="center"> <combobox x:name="workcellgroup" itemssource="{binding workcellgroupinfocollection}" selecteditem="{binding selectedworkcellgroup, mode=twoway}" displaymemberpath="name" /> </border> </grid>
code behind:
public partial class comboboxselecteditemtest : usercontrol { public comboboxselecteditemtest() { initializecomponent(); datacontext = new comboboxselecteditemtestviewmodel(); } } public abstract class filterbase { public string id { get; set; } public string name { get; set; } } public class workcellgroupinfo : filterbase { } public class workcellgroupinfocollection : observablecollection<workcellgroupinfo> { } public class comboboxselecteditemtestviewmodel : inotifypropertychanged { public workcellgroupinfocollection workcellgroupinfocollection { get; set; } public comboboxselecteditemtestviewmodel() { workcellgroupinfocollection = new workcellgroupinfocollection(); (int = 0; < 25; i++) { workcellgroupinfocollection.add(new workcellgroupinfo() { id = string.format("id #{0}", + 1), name = string.format("name #{0}", + 1) }); } selectedworkcellgroup = workcellgroupinfocollection.first(); } private workcellgroupinfo _selectedworkcellgroup; public workcellgroupinfo selectedworkcellgroup { { return _selectedworkcellgroup; } set { _selectedworkcellgroup = value; raisepropertychanged("selectedworkcellgroup"); } } public event propertychangedeventhandler propertychanged; protected void raisepropertychanged(string propertyname) { propertychangedeventhandler temp = propertychanged; if (temp != null) { temp(this, new propertychangedeventargs(propertyname)); } } }
Comments
Post a Comment