c# - Need help separating event driven code into layers that respect the MVVM pattern -
i have view titled newcalibrationview.xaml/.cs , has viewmodel newcalibrationviewmodel.cs
the xaml view:
<stackpanel grid.column="0" orientation="horizontal" horizontalalignment="left" > <label content="run time:" fontsize="16" fontweight="bold" margin="10,0,0,0"/> <textblock name="clocktextblock" text="00:00:00:00" fontsize="16" foreground="red" margin="5" fontweight="bold"/> </stackpanel> <stackpanel grid.column="1" orientation="horizontal" horizontalalignment="right"> <label content="sample count:" fontsize="16" fontweight="bold" margin="10,0,0,0"/> <textblock text="0" name="samplecountdigit" foreground="red" fontsize="16" fontweight="bold" margin="5"/> </stackpanel> as 1 can see, have textblock displays stop-watch of sorts, , presently code running stopwatch in code behind view (newcalibrationview.cs)
public partial class newcalibrationview: usercontrol { private dispatchertimer dt = new dispatchertimer(); private stopwatch stopwatch = new stopwatch(); private string _currenttime = string.empty; private int _samplecount = 0; public newcalibrationview() { initializecomponent(); dt.tick += new eventhandler(dt_tick); dt.interval = new timespan(0, 0, 0, 0, 1); } private void dt_tick(object sender, eventargs e) { if (stopwatch.isrunning) { timespan ts = stopwatch.elapsed; _currenttime = string.format("{0:00}:{1:00}:{2:00}", ts.hours, ts.minutes, ts.seconds); clocktextblock.text = _currenttime; if (ts.seconds%8 == 0) { _samplecount++; samplecountdigit.text = _samplecount.tostring(); } } } private void startbutton_click(object sender, routedeventargs e) { clocktextblock.foreground = brushes.green; stopwatch.start(); dt.start(); } because code updates view directly in event handler (dt.tick();) dispatchtimer's tick event, having hard time figuring out leave in code-behind , put in viewmodel.
given code-behind code have shown here, should go in view , should go in viewmodel?
to start, thought startbutton_click() should transformed command (which put in vm), if case doing alone mean have put declaration of dispatchtimer , stopwatch vm well, means rest of code (event hander, registration , on) have in vm.
does sound right?
if me, i'd move view model. i'd bind text properties of 2 textblock 2 strings on view model. said, bind button command property icommand on viewmodel. also, keep boolean property on viewmodel bind color of textblock (you'll need data triggers)
Comments
Post a Comment