MVVM in action
Let’s look at a very simple application that shows the user a quote of the day on the screen. When the user clicks a button on the screen, the application will fetch a quote of the day from an API and show it onscreen. Once the button is clicked, it should be hidden. The code-behind approach will show you how this app can be written without using the MVVM pattern, whereas the second example shows the same functionality implemented using MVVM with testability in mind.
The code-behind approach
In the following code snippet, there is no separation of concerns; all the code is handled in the code-behind of the XAML page. While this code seems to be doing what is expected, there is no easy, fast, or robust way to test whether it works. This is because all the logic is handled in the click event handler of the button.
In MainPage.xaml
, we define a Button
and a Label
:
<Grid> <Button ...