HomeContact

Implementing RelayCommand in WPF Using CommunityToolkit.Mvvm

By Shady Nagy
Published in dotnet
August 05, 2023
2 min read
Implementing RelayCommand in WPF Using CommunityToolkit.Mvvm

Table Of Contents

01
Introduction
02
Prerequisites
03
Setup
04
Single Object RelayCommand
05
Creating the TextDisplayWindow
06
List RelayCommand
07
Creating the ListDisplayWindow
08
Further Reading
09
Conclusion
10
Feedback and Questions

Introduction

In this tutorial, we will explore how to use the RelayCommand in a C# WPF application using the CommunityToolkit.Mvvm package. First, we’ll create a command that works with a single object, and then we’ll create a command that works with a list of objects.

Prerequisites

  1. Basic knowledge of C# and WPF.
  2. Visual Studio installed on your machine.
  3. .NET 5.0 or higher installed on your machine.

Setup

First, you need to create a new WPF project in Visual Studio. Once you’ve done that, we can begin adding the necessary packages.

Installing the CommunityToolkit.Mvvm Package

Right-click on your project in the Solution Explorer, then select “Manage NuGet Packages.” Click on the “Browse” tab and search for “CommunityToolkit.Mvvm.” Select the package and install it.

Single Object RelayCommand

Let’s start by creating a command that works with a single object.

public class MainViewModel : ObservableObject
{
private string _text;
public string Text
{
get => _text;
set => SetProperty(ref _text, value);
}
public ICommand ShowTextCommand => new RelayCommand<string>(ShowText);
private void ShowText(string text)
{
TextDisplayWindow textDisplayWindow = new TextDisplayWindow(text);
textDisplayWindow.ShowDialog();
}
}

You can now bind this command to a control in your XAML file. For instance, if you have a Button and a TextBox:

<TextBox x:Name="InputBox" Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" />
<Button Content="Show Text" Command="{Binding ShowTextCommand}" CommandParameter="{Binding Text}" />

Creating the TextDisplayWindow

Next, we need to create a new window named TextDisplayWindow. In the XAML of this window, add a TextBlock to display the passed string:

<Window x:Class="YourNamespace.TextDisplayWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Text Display" Height="300" Width="400">
<Grid>
<TextBlock x:Name="DisplayTextBlock" />
</Grid>
</Window>

In the code-behind for TextDisplayWindow, add a constructor that takes a string argument and sets the Text property of the TextBlock to this string:

public partial class TextDisplayWindow : Window
{
public TextDisplayWindow(string displayText)
{
InitializeComponent();
DisplayTextBlock.Text = displayText;
}
}

List RelayCommand

Let’s now create a command that works with a list of objects. For simplicity, we will use a list of strings.

public class MainViewModel : ObservableObject
{
private ObservableCollection<string> _items;
public ObservableCollection<string> Items
{
get => _items;
set => SetProperty(ref _items, value);
}
public ICommand ShowItemsCommand => new RelayCommand<ObservableCollection<string>>(ShowItems);
private void ShowItems(ObservableCollection<string> items)
{
ListDisplayWindow listDisplayWindow = new ListDisplayWindow(items);
listDisplayWindow.ShowDialog();
}
}

Creating the ListDisplayWindow

In your WPF project, add a new window named ListDisplayWindow. In the XAML of this window, add a ListBox that will be used to display the list of strings:

<Window x:Class="YourNamespace.ListDisplayWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="List Display" Height="300" Width="400">
<Grid>
<ListBox x:Name="DisplayListBox" />
</Grid>
</Window>

In the code-behind for ListDisplayWindow, add a constructor that takes a ObservableCollection<string> argument and sets the ItemsSource property of the ListBox to this collection:

public partial class ListDisplayWindow : Window
{
public ListDisplayWindow(ObservableCollection<string> displayList)
{
InitializeComponent();
DisplayListBox.ItemsSource = displayList;
}
}

You can now bind the ShowItemsCommand to a control in your XAML file. For example, a Button:

<ListBox x:Name="ItemsList" ItemsSource="{Binding Items}" />
<Button Content="Show Items" Command="{Binding ShowItemsCommand}" CommandParameter="{Binding Items}" />

Your application now has the ability to display a string in a new window when the “Show Text” button is clicked, and display a list of strings in another window when the “Show Items” button is clicked, showcasing the flexibility and power of RelayCommand in the context of a WPF application using the CommunityToolkit.Mvvm library.

Further Reading

To learn more about the topics covered in this post, consider checking out the following resources:

  1. Windows Presentation Foundation Documentation - The official Microsoft documentation for WPF, covering everything from basic usage to advanced topics.
  2. CommunityToolkit.Mvvm Documentation - The official documentation for the CommunityToolkit.Mvvm library.
  3. Understanding the MVVM pattern - A comprehensive guide to understanding and implementing the Model-View-ViewModel pattern in your applications.
  4. WPF Data Binding - An overview of data binding in WPF, which is an essential concept when working with RelayCommand and user interface data interaction.

Conclusion

In this post, we have explored the RelayCommand in a WPF application, covering both single object commands and list commands using the CommunityToolkit.Mvvm library. By understanding these concepts and implementing the RelayCommand in your WPF applications, you can create more interactive and user-friendly UIs.

Remember to practice and explore the wide range of options and scenarios where RelayCommand can be of great use. We hope this tutorial has given you a clear understanding and practical knowledge of how to use RelayCommand in your WPF applications. To further enhance your knowledge and skills in WPF and MVVM, we recommend checking out the resources listed in the Further Reading section.

Feedback and Questions

Your feedback is valuable to us! If you have any questions, comments, or suggestions for improvement regarding this tutorial, please don’t hesitate to get in touch. You can reach out through:

  1. Email: shady@shadynagy.com
  2. Twitter: @ShadyNagy_
  3. LinkedIn: Shady Nagy
  4. GitHub: ShadyNagy

We’re looking forward to hearing from you and helping you enhance your knowledge and skills in creating WPF applications using RelayCommand and the MVVM pattern!


Tags

#WPF#CSharp#RelayCommand#CommunityToolkitMvvm#MVVM#DataBinding#Commands#Microsoft

Share


Previous Article
Dynamically Injecting Environment Variables in a Dockerized Angular Application
Shady Nagy

Shady Nagy

Software Innovation Architect

Topics

AI
Angular
dotnet
GatsbyJS
Github
Linux
MS SQL
Oracle

Related Posts

Getting Started with NDepend A Comprehensive Guide to Boosting Code Quality
Getting Started with NDepend A Comprehensive Guide to Boosting Code Quality
July 03, 2024
4 min

Quick Links

Contact Us

Social Media