MVVM gridview binding to datatable WPF -
i new mvvm , databinding , having trouble binding gridview datatable dynamically. able column headers bind, no data being displayed in grid itself.
my model returns data table result of sql string passed it. viewmodel wraps datatable , gets bound view.
right trying display data populating gridview main window, headers being displayed.
i know there data in model.results datatable though.
my viewmodel:
public class resultsviewmodel { private datatable _dt; public resultsviewmodel() { datasource _ds = new datasource(); _dt = _ds.execute("select * tbl_users"); } public datatable results { { return _dt; } set { _dt = value; } } }
my code populate gridview mainwindow:
public mainwindow() { initializecomponent(); resultsview view = new resultsview(); resultsviewmodel model = new resultsviewmodel(); gridview grid = new gridview(); foreach (datacolumn col in model.results.columns) { grid.columns.add(new gridviewcolumn { header = col.columnname, displaymemberbinding = new binding(col.columnname) }); } view._listview.view = grid; view.datacontext = model; view.setbinding(listview.itemssourceproperty, new binding()); _placeholder.content = view; }
the resultsview xaml:
<usercontrol x:class="indevreporting.views.resultsview" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:ignorable="d" d:designheight="300" d:designwidth="300"> <grid> <listview x:name="_listview" /> </grid>
try setting data context model.results
.
ie change line:
view.datacontext = model;
to this:
view.datacontext = model.results;
generally create dependency property on view model , specify binding in xaml. grid should clever enough figure out columns draw:
<listview itemssource="{binding results}" /> public mainwindow() { initializecomponent(); // code instance , populate model this.datacontext = model; } public class resultsviewmodel : dependencyobject { public static readonly dependencyproperty resultsproperty = dependencyproperty.register("results", typeof(datatable) , typeof(resultsviewmodel)); public datatable results { { (datatable)getvalue(resultsproperty); } set { setvalue(resultsproperty, value); } } }
i've tapped out memory, apologies if code isn't right. easiest way declare new dependency property use propdp
code snippet. it's lot of syntax memorize.
Comments
Post a Comment