UWP Development, Creating Models

In recent years, the Universal Windows Platform (UWP) has played a significant role in providing a consistent user experience across various devices. One of the key elements of UWP development is creating an application’s data model. The data model defines how data is structured and managed within the application, clarifying the distinction between data and UI by applying the MVVM (Model-View-ViewModel) pattern. In this article, we will explore in detail how to structure a data model in a UWP application.

1. Understanding UWP and the MVVM Pattern

UWP is a platform for developing apps that can run on various Windows devices. MS’s MVVM pattern is useful for simplifying management and increasing code reusability. The MVVM pattern consists of three elements:

  • Model: Defines the data structure of the application. Manages interactions with the database and constraints on the data.
  • View: Comprises the elements of the user interface (UI) that interact with the user. In UWP, XAML is used to define the UI.
  • ViewModel: Manages data binding between the Model and View. The ViewModel acts as a bridge between the UI and data, managing the state of the UI.

2. Designing the Data Model

When designing a data model, you need to consider the structure of the required data and how to implement it in code. For instance, let’s assume we are creating a simple Todo list application. Each Todo item should have a title and a completion status.

2.1. Defining the Todo Model Class

using System;
using System.ComponentModel;

namespace TodoApp.Models
{
    public class TodoItem : INotifyPropertyChanged
    {
        private string title;
        private bool isCompleted;

        public string Title
        {
            get { return title; }
            set
            {
                if (title != value)
                {
                    title = value;
                    OnPropertyChanged("Title");
                }
            }
        }

        public bool IsCompleted
        {
            get { return isCompleted; }
            set
            {
                if (isCompleted != value)
                {
                    isCompleted = value;
                    OnPropertyChanged("IsCompleted");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

In the above code, we defined the TodoItem class. This class implements the INotifyPropertyChanged interface to notify the UI when a property changes. This enables data binding between the ViewModel and UI in the MVVM pattern.

3. Implementing the TodoListViewModel Class

Now it’s time to implement the ViewModel to manage the TodoItem model.

3.1. Defining the TodoListViewModel Class

using System.Collections.ObjectModel;

namespace TodoApp.ViewModels
{
    public class TodoListViewModel : INotifyPropertyChanged
    {
        private ObservableCollection<TodoItem> todoItems;
        private TodoItem selectedTodo;

        public ObservableCollection<TodoItem> TodoItems
        {
            get { return todoItems; }
            set
            {
                if (todoItems != value)
                {
                    todoItems = value;
                    OnPropertyChanged("TodoItems");
                }
            }
        }

        public TodoItem SelectedTodo
        {
            get { return selectedTodo; }
            set
            {
                if (selectedTodo != value)
                {
                    selectedTodo = value;
                    OnPropertyChanged("SelectedTodo");
                }
            }
        }

        public TodoListViewModel()
        {
            TodoItems = new ObservableCollection<TodoItem>();
        }

        public void AddTodo(string title)
        {
            TodoItems.Add(new TodoItem { Title = title, IsCompleted = false });
        }

        public void RemoveTodo(TodoItem todo)
        {
            if (TodoItems.Contains(todo))
            {
                TodoItems.Remove(todo);
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

In the code above, TodoListViewModel uses ObservableCollection to manage the list of Todo items. It also defines methods for adding and removing Todo items.

4. Building the UI with XAML

Now, let’s implement the user interface based on the model and ViewModel we created. In UWP, you can use XAML to build the UI.

4.1. Setting up MainPage.xaml

<Page
    x:Class="TodoApp.Views.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TodoApp.ViewModels"
    DataContext="{Binding TodoListViewModel, Source={StaticResource Locator}}">

    <StackPanel Margin="20">
        <TextBox x:Name="TodoInput" Placeholder="Enter a new todo item" />
        <Button Content="Add Todo" Click="AddTodo_Click" />
        <ListView ItemsSource="{Binding TodoItems}" SelectedItem="{Binding SelectedTodo}" >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <CheckBox IsChecked="{Binding IsCompleted}" />
                        <TextBlock Text="{Binding Title}" />
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackPanel>

The above XAML code allows users to add Todo items through a text box and button while displaying the list in a ListView. Each item has a checkbox to indicate its completion status.

5. Handling Events and Implementing Functionality

Now we will connect the UI and ViewModel, handling the button click event so that users can add Todo items.

5.1. Implementing the Event Handler in MainPage.xaml.cs

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace TodoApp.Views
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        private void AddTodo_Click(object sender, RoutedEventArgs e)
        {
            var viewModel = (TodoListViewModel)this.DataContext;
            string title = TodoInput.Text;

            if (!string.IsNullOrWhiteSpace(title))
            {
                viewModel.AddTodo(title);
                TodoInput.Text = string.Empty; // Clear the input field
            }
        }
    }
}

In the C# code above, we implemented the logic to add a Todo item when the button is clicked. After entering the title in the input field and clicking the button, the new Todo item is added to the ListView.

6. Summary and Optimization

The process of creating models in UWP applications is essential for structuring and managing data. The MVVM pattern allows for efficient interaction while maintaining a separation between data and UI. In this example, we implemented a simple Todo list application, which provided a deeper understanding of the structure and operation of UWP applications.

As we develop more complex applications in the future, it will be necessary to evolve and optimize the model and ViewModel. The most important thing is to create a user-friendly and intuitive UI, keeping in mind the user experience.

7. Additional Resources

If you want more in-depth information, please refer to the links below:

Through this article, I hope you have established a foundation for UWP development and have a clear understanding of how to design and implement a data model.