c# - How to binding XDocument element to combobox in MVVM? -
i have xdocument read xml file:
public observablecollection<product> getproducts() { observablecollection<product> _products = new observablecollection<product>(); xdocument doc = xdocument.load(@".\config\mcu.xml"); foreach (xelement productrow in doc.root.elements("mcu")) { var m = new product(productrow.element("mcuname").value, convert.touint32(productrow.element("mcunumber").value), convert.touint32(productrow.element("flashaddress").value), convert.touint32(productrow.element("pagecount").value), convert.touint32(productrow.element("pagesize").value), productrow.element("binfile").value, convert.touint32(productrow.element("ramcodeadd").value), convert.touint32(productrow.element("maincr").value), convert.touint32(productrow.element("crtrimmingadd").value), convert.touint32(productrow.element("crtrimminglength").value), convert.touint32(productrow.element("uidadd").value), convert.tobyte(productrow.element("uidlength").value), productrow.element("uid").value, productrow.element("userarea").value); _products.add(m); } return _products; }
now want binding xelement mcuname
combobox:
<combobox x:name="cb_mcutype" selecteditem="{binding mcuname, mode=twoway, updatesourcetrigger=propertychanged}" />
itemssouce in code behind:
public mainwindow() { initializecomponent(); cb_mcutype.itemssource = app.productdb.getproducts(); }
but doesn't work, combobox populate product
, how should fix this? thanks!
update:
thanks replies. suggested, write in mvvm, change original code:
xaml:
<combobox x:name="cb_mcutype" itemssource="{binding productslist}" selectedvalue="{binding selectedproduct}" displaymemberpath="mcuname" />
viewmodel:
public class mainviewmodel : inotifypropertychanged { private productdb pd = new productdb(); public mainviewmodel() { defaultvalue_load(); } public observablecollection<product> productslist { get; set; } private product _selectedproduct; public product selectedproduct { { return _selectedproduct; } set { _selectedproduct = value; notifypropertychanged("selectedproduct"); } } public void defaultvalue_load() { productslist = new observablecollectioin<product>(pd.getproducts()); } }
when create products
in getproducts()
provide mcuname
first parameter in constructor. following sample, i'll assume, there property mcuname
on every product:
public mainwindow() { initializecomponent(); cb_mcutype.itemssource = app.productdb.getproducts().select(p => p.mcuname); }
it worth mention, not clean mvvm implementation. should consider redesign application follow mvvm patter.
Comments
Post a Comment