How To: Create a ViewModel or Model from Classes
In this guide, we will look at how to create a new class element in Visual Studio and then create either a ViewModel or a Model for use in an Uno Platform application.
For the following steps, let's assume the page that the element to be created belongs to is called SamplePage.xaml
Add a new item (for use as Model or ViewModel):
- Right-click on the Presentation folder in the Solution Explorer on the right
- Select Add
- Then click on New Item

Create a Class element:
- Select the
Classelement in the list and name it according to the naming conventions:
Your application uses:
- Mvvm:
SampleViewModel.cs - Mvux:
SampleModel.cs
- Select the
Now click Add.

To create a Model suitable for Mvux:
- Insert
partialbefore the currentclass. - Replace
classwithrecord - With the snippet shortcut
ctoryou can also automatically insert a (secondary) constructor.

Note
In Mvux, Models are defined as record types to leverage immutability and value-based equality, which are beneficial for state management in applications.
Using partial is essential in Mvux Models to enable code generation features provided by the framework, such as automatic property change notifications and other boilerplate code reductions.
Caution
Just like in regular C# classes, Mvux Models or Services can also have primary constructors, which will by default produce the parameters as properties of the record type.
A potential downside of this is, that a INavigator parameter in the primary constructor would also be a property of the Model, which is not what we normally want as part of our Model's public API.
You should prefer defining those Service defining parameters in a secondary constructor and keep them as private readonly fields.
Note
You are free to use the primary constructor in Uno ViewModels or Models, but note that using Uno.Extensions.Navigation you can not have parameters in the page constructor.
