data binding - How to Bind a TextBox in DataGrid to a List in Wpf? -
am working on new wpf project , struggling binding textbox in datagrid list of objects in wpf. can me fix?
this code (simplified version) generate datagrid rows binding orders object. user can changed order items , should bind underline object. once user clicked read orders button displaying changes in textblock. issue: changes in textbox not updating orders object.
observablecollection<stxordr> orders = new observablecollection<stxordr>(); private void window_initialized(object sender, eventargs e) { orders.add(new stxordr() { id = 1, desc = "order-#1", item1 = "11", item2 = "12", item3 = "13" }); orders.add(new stxordr() { id = 2, desc = "order-#2", item1 = "21", item2 = "22", item3 = "23" }); orders.add(new stxordr() { id = 3, desc = "order-#3", item1 = "31", item2 = "32", item3 = "33" }); dg2.itemssource = orders; } private void readupdatedorders(object sender, routedeventargs e) { txtblk.text = ""; foreach (stxordr odr in orders) { txtblk.text += string.format("{0}: {1} - {2} - {3}\n", odr.desc, odr.item1, odr.item2, odr.item3); } }
window xml
<datagrid x:name="dg2" horizontalalignment="left" margin="21,295,0,0" verticalalignment="top" height="230" width="451" autogeneratecolumns="false" itemssource="{binding source=orders}" > <datagrid.columns> <datagridtextcolumn header="id" binding="{binding id}" /> <datagridtextcolumn header="desc" binding="{binding desc}" width="80"/> <datagridtextcolumn header="item 1" binding="{binding item1}" width="60"/> <datagridtextcolumn header="item 2" binding="{binding item2}" width="60"/> <datagridtemplatecolumn header="item 3" > <datagridtemplatecolumn.celltemplate> <datatemplate> <textbox text="{binding item3, mode=onewaytosource}" width="60" /> </datatemplate> </datagridtemplatecolumn.celltemplate> </datagridtemplatecolumn> </datagrid.columns> </datagrid> <textblock x:name="txtblk" horizontalalignment="left" margin="489,295,0,0" textwrapping="wrap" text=" updated order details:" verticalalignment="top" height="176" width="408" background="#fffffcbc"/> <button x:name="btn2_copy" content="read orders" horizontalalignment="left" margin="489,476,0,0" verticalalignment="top" width="94" click="readupdatedorders"/>
screenshot of ui window
i think things looks correct. make sure orders.cs implements inotifypropertychanged , line of code
<textbox text="{binding item3, mode=onewaytosource}" width="60" />
is updated mode = twoway , updatesourcetrigger = propertychanged. change to
<textbox text="{binding item3, mode=twoway, updatesourcetrigger=propertychanged}" width="60" />
Comments
Post a Comment