### Registering dependencies with SimpleIoc Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/migratingfrommvvmlight Example of registering dependencies using MvvmLight's SimpleIoc. This is the pattern you'll be migrating from. ```csharp public void RegisterServices() { SimpleIoc.Default.Register(); SimpleIoc.Default.Register(() => new DialogService()); } ``` -------------------------------- ### Standard Command Setup Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/generators/overview This demonstrates the conventional method for creating a command, involving a private method for execution and manual instantiation of `RelayCommand` with a backing field. ```csharp private void SayHello() { Console.WriteLine("Hello"); } private ICommand? sayHelloCommand; public ICommand SayHelloCommand => sayHelloCommand ??= new RelayCommand(SayHello); ``` -------------------------------- ### Standard Observable Property Setup Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/generators/overview This is the traditional way to set up an observable property, requiring manual implementation of the getter, setter, and property change notification. ```csharp private string? name; public string? Name { get => name; set => SetProperty(ref name, value); } ``` -------------------------------- ### Install MVVM Toolkit via .NET CLI Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/migratingfrommvvmbasic Use the .NET CLI to add the CommunityToolkit.Mvvm NuGet package to your project. Ensure you specify the desired version. ```bash dotnet add package CommunityToolkit.Mvvm --version 8.1.0 ``` -------------------------------- ### Unregistering dependencies with SimpleIoc Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/migratingfrommvvmlight Example of how to unregister a dependency with MvvmLight's SimpleIoc. The MVVM Toolkit's Ioc does not have a direct replacement for this. ```csharp SimpleIoc.Default.Unregister(); ``` -------------------------------- ### Implementing OnChanging and OnChanged (New Value Only) Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/generators/observableproperty Example demonstrating how to implement the partial methods OnNameChanging and OnNameChanged to execute logic based solely on the new value when the 'Name' property changes. ```csharp [ObservableProperty] private string? name; partial void OnNameChanging(string? value) { Console.WriteLine($"Name is about to change to {value}"); } partial void OnNameChanged(string? value) { Console.WriteLine($"Name has changed to {value}"); } ``` -------------------------------- ### Install MVVM Toolkit via PackageReference Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/migratingfrommvvmlight Add this XML element to your project file to include the CommunityToolkit.Mvvm NuGet package using the PackageReference format. ```xml ``` -------------------------------- ### MVVMTK0036 Error Example Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/generators/errors/mvvmtk0036 This code snippet demonstrates the MVVMTK0036 error caused by a missing `using` directive for the `JsonIgnore` attribute. ```C# using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; namespace MyApp; public partial class SampleViewModel : ObservableObject { [ObservableProperty] private int counter; [RelayCommand] [property: JsonIgnore] private void IncrementCounter() { Counter++; } } ``` -------------------------------- ### Install MVVM Toolkit via PackageReference Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/migratingfrommvvmbasic Add the CommunityToolkit.Mvvm NuGet package to your project using the PackageReference XML format. Specify the version required for your project. ```xml ``` -------------------------------- ### Asynchronous Request Message Example Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/messenger Define and use an asynchronous request message to get a User object. Register a receiver that replies with a `Task`. The request can be directly awaited, simplifying asynchronous data retrieval. ```csharp public class LoggedInUserRequestMessage : AsyncRequestMessage { } WeakReferenceMessenger.Default.Register(this, (r, m) => { m.Reply(r.GetCurrentUserAsync()); }); User user = await WeakReferenceMessenger.Default.Send(); ``` -------------------------------- ### Synchronous Request Message Example Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/messenger Define and use a synchronous request message to get a User object. Register a receiver to handle the request and reply with the current user. The `RequestMessage` class ensures a response is received or throws an exception. ```csharp public class LoggedInUserRequestMessage : RequestMessage { } WeakReferenceMessenger.Default.Register(this, (r, m) => { m.Reply(r.CurrentUser); }); User user = WeakReferenceMessenger.Default.Send(); ``` -------------------------------- ### Implementing OnChanging and OnChanged (Old and New Values) Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/generators/observableproperty This example shows how to implement the overloads of OnSelectedItemChanging and OnSelectedItemChanged to access both the old and new values, useful for updating related state. ```csharp [ObservableProperty] private ChildViewModel? selectedItem; partial void OnSelectedItemChanging(ChildViewModel? oldValue, ChildViewModel? newValue) { if (oldValue is not null) { oldValue.IsSelected = true; } if (newValue is not null) { newValue.IsSelected = true; } } ``` -------------------------------- ### Command Setup with Source Generator Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/generators/overview The `RelayCommand` attribute streamlines command creation. By annotating a method with `[RelayCommand]`, the source generator automatically creates the associated command property. ```csharp [RelayCommand] private void SayHello() { Console.WriteLine("Hello"); } ``` -------------------------------- ### SubredditWidgetViewModel Setup with AsyncRelayCommand and Observable Properties Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/puttingthingstogether This viewmodel manages subreddit posts, exposing an async command to load posts and observable properties for the post collection, subreddits, and selected items. Use `SetProperty` for observable properties and `AsyncRelayCommand` for asynchronous operations. ```csharp public sealed class SubredditWidgetViewModel : ObservableRecipient { /// /// Creates a new instance. /// public SubredditWidgetViewModel() { LoadPostsCommand = new AsyncRelayCommand(LoadPostsAsync); } /// /// Gets the instance responsible for loading posts. /// public IAsyncRelayCommand LoadPostsCommand { get; } /// /// Gets the collection of loaded posts. /// public ObservableCollection Posts { get; } = new ObservableCollection(); /// /// Gets the collection of available subreddits to pick from. /// public IReadOnlyList Subreddits { get; } = new[] { "microsoft", "windows", "surface", "windowsphone", "dotnet", "csharp" }; private string selectedSubreddit; /// /// Gets or sets the currently selected subreddit. /// public string SelectedSubreddit { get => selectedSubreddit; set => SetProperty(ref selectedSubreddit, value); } private object selectedPost; /// /// Gets or sets the currently selected subreddit. /// public object SelectedPost { get => selectedPost; set => SetProperty(ref selectedPost, value, true); } /// /// Loads the posts from a specified subreddit. /// private async Task LoadPostsAsync() { // TODO... } } ``` -------------------------------- ### Configure Service Provider for Settings Service Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/puttingthingstogether This C# code demonstrates how to configure the service provider to register a singleton instance of `SettingsService` as `ISettingsService` and a transient instance of `PostWidgetViewModel`. This setup ensures that the UWP-specific `SettingsService` is used when resolving `ISettingsService` on UWP platforms. ```csharp /// /// Gets the instance to resolve application services. /// public IServiceProvider Services { get; } /// /// Configures the services for the application. /// private static IServiceProvider ConfigureServices() { var services = new ServiceCollection(); services.AddSingleton(); services.AddTransient(); return services.BuildServiceProvider(); } ``` -------------------------------- ### XAML Binding for Command and Parameter Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/generators/relaycommand This XAML example demonstrates how to bind a Button's Command and CommandParameter to properties in the ViewModel. The Command is linked to the generated RelayCommand, and the CommandParameter is bound to the selected user. ```xml