.net - How to populate a WPF grid based on a 2-dimensional array -
i have 2-dimensional array of objects , want databind each 1 cell in wpf grid. have working doing of procedurally. create correct number of row , column definitions, loop through cells , create controls , set correct bindings each one.
at minimum able use template specify controls , bindings in xaml. ideally rid of procedural code , databinding, i'm not sure that's possible.
here code using:
public void bindgrid() { m_grid.children.clear(); m_grid.columndefinitions.clear(); m_grid.rowdefinitions.clear(); (int x = 0; x < mefgrid.width; x++) { m_grid.columndefinitions.add(new columndefinition() { width = new gridlength(1, gridunittype.star), }); } (int y = 0; y < mefgrid.height; y++) { m_grid.rowdefinitions.add(new rowdefinition() { height = new gridlength(1, gridunittype.star), }); } (int x = 0; x < mefgrid.width; x++) { (int y = 0; y < mefgrid.height; y++) { cell cell = (cell)mefgrid[x, y]; solidcolorbrush brush = new solidcolorbrush(); var binding = new binding("on"); binding.converter = new boolcolorconverter(); binding.mode = bindingmode.oneway; bindingoperations.setbinding(brush, solidcolorbrush.colorproperty, binding); var rect = new rectangle(); rect.datacontext = cell; rect.fill = brush; rect.setvalue(grid.rowproperty, y); rect.setvalue(grid.columnproperty, x); m_grid.children.add(rect); } } }
the purpose of grid not real databinding, panel. listing down easiest way accomplish visualization of 2 dimensional list
<window.resources> <datatemplate x:key="datatemplate_level2"> <button content="{binding}" height="40" width="50" margin="4,4,4,4"/> </datatemplate> <datatemplate x:key="datatemplate_level1"> <itemscontrol itemssource="{binding}" itemtemplate="{dynamicresource datatemplate_level2}"> <itemscontrol.itemspanel> <itemspaneltemplate> <stackpanel orientation="horizontal"/> </itemspaneltemplate> </itemscontrol.itemspanel> </itemscontrol> </datatemplate> </window.resources> <grid> <itemscontrol x:name="lst" itemtemplate="{dynamicresource datatemplate_level1}"/> </grid>
and in code behind set itemssource of lst twodimentional data structure.
public window1() { list<list<int>> lsts = new list<list<int>>(); (int = 0; < 5; i++) { lsts.add(new list<int>()); (int j = 0; j < 5; j++) { lsts[i].add(i * 10 + j); } } initializecomponent(); lst.itemssource = lsts; }
this gives following screen output. can edit datatemplate_level2 add more specific data of object.
Comments
Post a Comment