Windows Presentation Foundation (WPF) is a UI development platform based on the .NET framework that enables the creation of user interfaces (UI) and implements elegant designs through data binding and styling. Today, we will develop an application that displays a simple product list and details using the MVVM (Model-View-ViewModel) design pattern.
1. Understanding MVVM Architecture
The MVVM pattern divides the structure of the application into three main components, increasing maintainability.
- Model: Responsible for the data structure and business logic of the application. This includes functionalities for fetching data from the database or processing data.
- View: Contains the UI components displayed to the user, usually written in XAML files.
- ViewModel: Acts as an intermediary between the Model and the View, providing processed data to enable user interactions in the View.
2. Setting Up the Example Project
Open Visual Studio and create a new WPF application project. Name the project ProductDisplayApp.
2.1 Project Structure
After creating the project, the basic folder structure is as follows:
- Views: Contains UI-related XAML files.
- ViewModels: Contains ViewModel classes.
- Models: Contains data structure and business logic classes.
2.2 Installing NuGet Packages
In this example, we will use the MVVM Light Toolkit, which is a tool that simplifies the implementation of the MVVM architecture. Install MVVM Light Toolkit from the NuGet Package Manager.
3. Creating the Model
Create a Product class that represents product information in the Models folder.
csharp
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
}
4. Writing the ViewModel
Create a ProductViewModel in the ViewModels folder to manage the product list and details of the selected product.
csharp
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System.Collections.ObjectModel;
using System.Linq;
public class ProductViewModel : ViewModelBase
{
private ObservableCollection _products;
private Product _selectedProduct;
public ObservableCollection Products
{
get => _products;
set => Set(ref _products, value);
}
public Product SelectedProduct
{
get => _selectedProduct;
set => Set(ref _selectedProduct, value);
}
public ProductViewModel()
{
LoadProducts();
}
private void LoadProducts()
{
Products = new ObservableCollection
{
new Product { Id = 1, Name = "Product 1", Description = "Description of Product 1", Price = 10.99M },
new Product { Id = 2, Name = "Product 2", Description = "Description of Product 2", Price = 15.49M },
new Product { Id = 3, Name = "Product 3", Description = "Description of Product 3", Price = 7.99M }
};
}
}
5. Writing the View (XAML)
Now, let’s write the view to display the product list and details. Open the MainWindow.xaml file and add the following code.
xml
6. Running and Testing
When you run the program, the product list will be displayed on the left side and the details of the selected product will appear on the right. Selecting a product from the list shows its name, description, and price.
7. Additional Feature: Integrating with a Database
Now, let’s add a simple feature to integrate the product list with a database. We will use Entity Framework. Run the following command in the package manager console to install it:
bash
Install-Package EntityFramework
Then, add database-related properties above the Product class and create a DbContext class to load the product list from the database.
7.1 Setting Up DbContext
csharp
using System.Data.Entity;
public class ProductContext : DbContext
{
public DbSet Products { get; set; }
}
7.2 Updating Product Load
Update the LoadProducts method of the ViewModel class with code to load products from the database.
csharp
private void LoadProducts()
{
using (var context = new ProductContext())
{
Products = new ObservableCollection(context.Products.ToList());
}
}
8. Exception Handling and Enhancing User Experience
Add exception handling for cases where the user has not selected a product. Also, add handling for when the selected product is null.
csharp
public Product SelectedProduct
{
get => _selectedProduct;
set
{
if (Set(ref _selectedProduct, value))
{
// Notify property change for the details
RaisePropertyChanged(nameof(SelectedProduct));
}
}
}
9. Conclusion
In this tutorial, we learned how to structure a WPF application using the MVVM pattern. Through the entire process of displaying a product list in the UI and representing the details of the selected product, we experienced the advantages of MVVM and WPF’s data binding capabilities. This structure can enhance the maintainability and scalability of the application.
10. Next Steps
Moreover, additional functionalities such as connecting to the database, creating and modifying products through user input, etc., can be added to expand the application. We encourage you to continue developing more robust and flexible applications by utilizing the MVVM pattern to separate business logic from the UI.