xaml - .Net 4 WPF DataGrid's ItemsSource - works programmatically, but not declaratively -
i writing wpf programme using c# , targeting .net 4.0. trying follow mvvm pattern, view (code-behind) has minimal-to-no code.
i have list<myrecord>
want display in gui using datagrid
. in xaml, have following:
<datagrid x:name="recordgrid" ...> <datagrid.columns> <datagridtextcolumn binding="{binding recid}" header="record id"/> <datagridtextcolumn binding="{binding name}" header="name"/> </datagrid.columns> </datagrid>
all that's left bind grid info collection.
when bind in code-behind file, works fine:
recordgrid.itemssource = myrecordlist;
however, prefer bind declaratively in xaml. tried this:
<datagrid x:name="recordgrid" itemssource="{binding myrecordlist}" ...>
but silently doesn't work. there no xaml binding error message when datagrid loads. set breakpoint on myrecordlist's get
method, , it's never invoked long itemssource defined declaratively.
how can datagrid pull myrecordlist
via xaml?
you need set datacontext if want binding work... mvvm pattern has view , viewmodel. view ui - e.g. window (let's phone call mainwindow) , viewmodel have recordgrid
property , theother commands/properties (let's phone call class mainwindowviewmodel)
you need connect them both, done specifying in view, datacontext
(in our case mainwindowviewmodel class).
so you'll want in view's constructor:
public mainwindow() { this.datacontext = new mainwindowviewmodel(); initializecomponent();
.net xaml mvvm wpfdatagrid
No comments:
Post a Comment