i'm trying use mvvm design pattern. searched , read many mvvm documents , examples, it's difficult me.
i want navigate , show view main window code isn't working.
without <window.resources> ~ </window.resources>
part, contentcontrol elements shows text 'myproject.viewmodel.authviewmodel'.
but if put <window.resources>
part, nullreferenceexception: object reference not set instance of object. @ myproject.helper.delegatecommand.canexecute(object parameter)
error occurs
what wrong?
mainviewmodel.cs
public class mainviewmodel : viewmodelbase { private icommand _changeviewcommand; private viewmodelbase _currentviewmodel; private list<viewmodelbase> _viewmodels; public mainviewmodel(){ viewmodels.add(new authviewmodel()); currentviewmodel = viewmodels[0]; } #region commands public icommand changeviewcommand { { if (_changeviewcommand == null) { _changeviewcommand = new delegatecommand( param => changeviewmodel((viewmodelbase)param), param => param viewmodelbase ); } return _changeviewcommand; } } #endregion #region properties public list<viewmodelbase> viewmodels { { if (_viewmodels == null) _viewmodels = new list<viewmodelbase>(); return _viewmodels; } } public viewmodelbase currentviewmodel { { return _currentviewmodel; } set { if(_currentviewmodel != value) { _currentviewmodel = value; raisepropertychanged("currentviewmodel"); } } } #endregion private void changeviewmodel(viewmodelbase _viewmodel) { if (_viewmodel != null && !viewmodels.contains(_viewmodel)) viewmodels.add(_viewmodel); currentviewmodel = viewmodels.firstordefault(_vm => _vm == _viewmodel); }
mainview.xaml
<window x:class="myproject.view.mainview" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:v="clr-namespace:myproject.view" xmlns:vm="clr-namespace:myproject.viewmodel" xmlns:mp="clr-namespace:myproject" title="myproject" height="630" width="460" windowstartuplocation="centerscreen" snapstodevicepixels="true"> <window.resources> <datatemplate datatype="{x:type vm:mainviewviewmodel}"> <v:beamview /> </datatemplate> <datatemplate datatype="{x:type vm:authviewmodel}"> <v:authview/> </datatemplate> </window.resources> <window.datacontext> <vm:mainviewmodel/> </window.datacontext> <grid> <contentcontrol content="{binding currentviewmodel}" horizontalcontentalignment="stretch" verticalcontentalignment="stretch" verticalalignment="stretch" horizontalalignment="stretch"/> </grid> </window>
dayum. <datetemplate>
didn't cause problem.
i wrote wrong code @ delegatecommand
class
public override bool canexecute(object parameter) { if (parameter != null) // hell ? return true; return _canexecute(parameter); }
and fixed it
public override bool canexecute(object parameter) { if (parameter == null) return true; return _canexecute(parameter); }
Comments
Post a Comment