### Complete iOS Info.plist Example
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/views/camera-view
A complete `Info.plist` example for iOS, including camera and optional microphone usage descriptions.
```XML
UIDeviceFamily12UIRequiredDeviceCapabilitiesarm64UISupportedInterfaceOrientationsUIInterfaceOrientationPortraitUIInterfaceOrientationLandscapeLeftUIInterfaceOrientationLandscapeRightUISupportedInterfaceOrientations~ipadUIInterfaceOrientationPortraitUIInterfaceOrientationPortraitUpsideDownUIInterfaceOrientationLandscapeLeftUIInterfaceOrientationLandscapeRightXSAppIconAssetsAssets.xcassets/appicon.appiconsetNSCameraUsageDescriptionPROVIDE YOUR REASON HERENSMicrophoneUsageDescriptionPROVIDE YOUR REASON HERE
```
--------------------------------
### Complete Android Manifest Example
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/views/camera-view
A comprehensive example of the `AndroidManifest.xml` file including camera and optional microphone permissions.
```XML
```
--------------------------------
### Completed Package Tag Example
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/alerts/toast
An example of a completed opening `` tag in `Package.appxmanifest` that includes support for Snackbar by adding required namespaces.
```xml
```
--------------------------------
### Set VerticalOptions to Start
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/markup/extensions/view-extensions
Use Top to set the View.VerticalOptions property to LayoutOptions.Start.
```csharp
new Label().Top()
```
--------------------------------
### Start Speech to Text Listening
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/essentials/speech-to-text
Starts the speech-to-text listening process after verifying permissions. Handles permission denial with a toast notification. Subscribes to result update and completion events.
```csharp
async Task StartListening(CancellationToken cancellationToken)
{
var isGranted = await speechToText.RequestPermissions(cancellationToken);
if (!isGranted)
{
await Toast.Make("Permission not granted").Show(CancellationToken.None);
return;
}
speechToText.RecognitionResultUpdated += OnRecognitionTextUpdated;
speechToText.RecognitionResultCompleted += OnRecognitionTextCompleted;
await speechToText.StartListenAsync(new SpeechToTextOptions { Culture = CultureInfo.CurrentCulture, ShouldReportPartialResults = true }, CancellationToken.None);
}
```
--------------------------------
### Start Camera Preview Method
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/views/camera-view
This C# snippet demonstrates how to use the StartCameraPreview method to initiate the camera preview. It includes basic error handling and a timeout mechanism.
```C#
async void HandleStartCameraPreviewButtonTapped(object? sender, EventArgs e)
{
try
{
var startCameraPreviewTCS = new CancellationTokenSource(TimeSpan.FromSeconds(3));
// Use the Camera field defined above in XAML (``)
await Camera.StartCameraPreview(startCameraPreviewTCS.Token);
}
catch(Exception e)
{
// Handle Exception
Trace.WriteLine(e);
}
}
```
--------------------------------
### Using MultiValidationBehavior in C#
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/behaviors/multi-validation-behavior
Demonstrates how to use the MultiValidationBehavior by defining individual validation rules and applying them to an Entry control. This example shows the setup of styles and multiple CharactersValidationBehavior instances.
```csharp
class MultiValidationBehaviorPage : ContentPage
{
public MultiValidationBehaviorPage()
{
var entry = new Entry
{
IsPassword = true,
Placeholder = "Password"
};
var validStyle = new Style(typeof(Entry));
validStyle.Setters.Add(new Setter
{
Property = Entry.TextColorProperty,
Value = Colors.Green
});
var invalidStyle = new Style(typeof(Entry));
invalidStyle.Setters.Add(new Setter
{
Property = Entry.TextColorProperty,
Value = Colors.Red
});
var atLeastOneDigit = new CharactersValidationBehavior
{
Flags = ValidationFlags.ValidateOnValueChanged,
CharacterType = CharacterType.Digit,
MinimumCharacterCount = 1
};
MultiValidationBehavior.SetError(atLeastOneDigit, "1 digit");
var atLeastUpperCase = new CharactersValidationBehavior
{
Flags = ValidationFlags.ValidateOnValueChanged,
CharacterType = CharacterType.UppercaseLetter,
MinimumCharacterCount = 1
};
MultiValidationBehavior.SetError(atLeastUpperCase, "1 upper case");
var atLeastOneSymbol = new CharactersValidationBehavior
{
Flags = ValidationFlags.ValidateOnValueChanged,
CharacterType = CharacterType.NonAlphanumericSymbol,
MinimumCharacterCount = 1
};
MultiValidationBehavior.SetError(atLeastOneSymbol, "1 symbol");
var atLeastEightCharacters = new CharactersValidationBehavior
{
Flags = ValidationFlags.ValidateOnValueChanged,
CharacterType = CharacterType.Any,
MinimumCharacterCount = 1
};
MultiValidationBehavior.SetError(atLeastEightCharacters, "8 characters");
var multiValidationBehavior = new MultiValidationBehavior
{
InvalidStyle = invalidStyle,
ValidStyle = validStyle,
Flags = ValidationFlags.ValidateOnValueChanged,
Children =
{
atLeastOneDigit,
atLeastUpperCase,
atLeastOneSymbol,
atLeastEightCharacters
}
};
entry.Behaviors.Add(multiValidationBehavior);
Content = entry;
}
}
```
--------------------------------
### Set Label HorizontalOptions to Start
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/markup/extensions/view-extensions
Use the Start extension method to set the HorizontalOptions property of a Label to LayoutOptions.Start.
```csharp
new Label().Start()
```
--------------------------------
### Basic XAML Structure
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/behaviors/maximum-length-reached-behavior
An example of a basic XAML ContentPage structure.
```XAML
```
--------------------------------
### Bind Button to Start Camera Preview Command
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/views/camera-view
This XAML snippet shows how to bind a Button's Command property to the StartCameraPreviewCommand of a CameraView. This allows users to start the camera preview by tapping the button.
```XAML
```
--------------------------------
### Start Video Recording to MemoryStream
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/views/camera-view
This C# method shows how to record a short video directly into a MemoryStream. The recording is stopped, and the stream is then saved to a file.
```C#
async void StartCameraRecording(object? sender, EventArgs e)
{
await Camera.StartVideoRecording(CancellationToken.None);
await Task.Delay(TimeSpan.FromSeconds(3));
var threeSecondVideoRecordingStream = await Camera.StopVideoRecording(CancellationToken.None);
await FileSaver.SaveAsync("recording.mp4", threeSecondVideoRecordingStream);
}
```
--------------------------------
### Using SetFocusOnEntryCompletedBehavior with C# Markup
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/behaviors/set-focus-when-entry-completed-behavior
This example utilizes the CommunityToolkit.Maui.Markup package for a more concise C# implementation of the SetFocusOnEntryCompletedBehavior.
```C#
using CommunityToolkit.Maui.Markup;
class SetFocusOnEntryCompletedBehaviorPage : ContentPage
{
public SetFocusOnEntryCompletedBehaviorPage()
{
Content = new VerticalStackLayout
{
Spacing = 12,
Children =
{
new Entry { ReturnType = ReturnType.Next }
.Assign(out var firstName)
.Placeholder("Entry 1 (Tap `Next` on the keyboard when finished)"),
new Entry()
.Assign(out var lastName)
}
};
SetFocusOnEntryCompletedBehavior.SetNextElement(firstName, lastName);
}
}
```
--------------------------------
### Using UserStoppedTypingBehavior with C# Markup
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/behaviors/user-stopped-typing-behavior
This example utilizes the CommunityToolkit.Maui.Markup package for a more concise C# implementation of the UserStoppedTypingBehavior. It chains behavior configuration and binding directly to the Entry control.
```C#
using CommunityToolkit.Maui.Markup;
class UserStoppedTypingBehaviorPage : ContentPage
{
public UserStoppedTypingBehaviorPage()
{
Content = new Entry
{
Placeholder = "Start typing when you stop the behavior will trigger..."
}
.Behaviors(new UserStoppedTypingBehavior
{
StoppedTypingTimeThreshold = 1000,
MinimumLengthThreshold = 3,
ShouldDismissKeyboardAutomatically = true
}.Bind(UserStoppedTypingBehavior.CommandProperty,
getter: static (ViewModel vm) => vm.SearchCommand,
source: this.BindingContext,
mode: BindingMode.OneTime));
}
}
```
--------------------------------
### Add SelectAllTextBehavior in C#
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/behaviors/select-all-text-behavior
This example shows how to instantiate and add the SelectAllTextBehavior to an Entry control programmatically using C#.
```C#
class SelectAllTextBehaviorPage : ContentPage
{
public SelectAllTextBehaviorPage()
{
var entry = new Entry();
var selectAllTextBehavior = new SelectAllTextBehavior();
entry.Behaviors.Add(selectAllTextBehavior);
Content = entry;
}
}
```
--------------------------------
### Using StateContainer with C# Markup
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/layouts/statecontainer
Example of creating a UI with StateContainer using C# Markup. This demonstrates how to bind state properties and define state views programmatically.
```C#
using CommunityToolkit.Maui.Layouts;
using CommunityToolkit.Maui.Markup;
BindingContext = new StateContainerViewModel();
Content = new VerticalStackLayout()
{
new Label()
.Text("Default Content"),
new Button()
.Text("Change State")
.Bind(
Button.CommandProperty,
static (StateContainerViewModel vm) => vm.ChangeStateCommand,
mode: BindingMode.OneTime)
}.Bind(
StateContainer.CurrentStateProperty,
static (StateContainerViewModel vm) => vm.CurrentState,
static (StateContainerViewModel vm, string currentState) => vm.CurrentState = currentState)
.Bind(
StateContainer.CanStateChangeProperty,
static (StateContainerViewModel vm) => vm.CanStateChange,
static (StateContainerViewModel vm, bool canStateChange) => vm.CanStateChange = canStateChange)
.Assign(out VerticalStackLayout layout);
var stateViews = new List()
{
//States.Loading
new VerticalStackLayout()
{
new ActivityIndicator() { IsRunning = true },
new Label().Text("Loading Content")
},
//States.Success
new Label().Text("Success!")
};
StateView.SetStateKey(stateViews[0], States.Loading);
StateView.SetStateKey(stateViews[1], States.Success);
StateContainer.SetStateViews(layout, stateViews);
static class States
{
public const string Loading = nameof(Loading);
public const string Success = nameof(Success);
}
```
--------------------------------
### Request Storage Read Permission
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/essentials/folder-picker
Before picking a folder, you must manually request the Permissions.StorageRead permission. This is a necessary setup step for folder selection.
```csharp
var readPermissionsRequest = await Permissions.RequestAsync();
```
--------------------------------
### Populating Grid with Enum-Defined Rows and Columns
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/markup/extensions/grid-extensions
This example demonstrates how to use enums to define RowDefinitions, ColumnDefinitions, and assign controls to specific rows and columns within a Grid.
```csharp
using static CommunityToolkit.Maui.Markup.GridRowsColumns;
class LoginPage : ContentPage
{
public LoginPage()
{
Content = new Grid
{
RowDefinitions = Rows.Define(
(Row.Username, 30),
(Row.Password, 30),
(Row.Submit, Star)),
ColumnDefinitions = Columns.Define(
(Column.Description, Star),
(Column.UserInput, Star)),
Children =
{
new Label()
.Text("Username")
.Row(Row.Username).Column(Column.Description),
new Entry()
.Placeholder("Username")
.Row(Row.Username).Column(Column.UserInput),
new Label()
.Text("Password")
.Row(Row.Password).Column(Column.Description),
new Entry { IsPassword = true }
.Placeholder("Password")
.Row(Row.Password).Column(Column.UserInput),
new Button()
.Text("Submit")
.Row(Row.Password).RowSpan(All())
}
}
}
enum Row { Username, Password, Submit }
enum Column { Description, UserInput }
}
```
--------------------------------
### Updated Package.appxmanifest for Snackbar Support
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/alerts/toast
This is an example of an updated `Package.appxmanifest` file configured to support `Snackbar` notifications on Windows. It includes necessary namespaces and capabilities for toast activation.
```xml
$placeholder$Microsoft$placeholder$.png
```
--------------------------------
### Complete Grid Example with Row and Column Definitions
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/markup/extensions/grid-extensions
Demonstrates creating a Grid with specific row and column definitions and populating it with Labels, utilizing the `Row()` and `Column()` extension methods for positioning.
```csharp
// Add this using static to enable Columns.Define and Rows.Define
using static CommunityToolkit.Maui.Markup.GridRowsColumns;
// ...
new Grid
{
ColumnDefinitions = Columns.Define(30, Star, Stars(2)),
RowDefinitions = Rows.Define(Auto, Star),
Children =
{
new Label()
.Text("This Label is in Row 0 Column 0")
.Row(0).Column(0)
new Label()
.Text("This Label is in Row 0 Column 1")
.Row(0).Column(1)
new Label()
.Text("This Label is in Row 0 Column 2")
.Row(1).Column(2)
new Label()
.Text("This Label is in Row 1 Column 0")
.Row(1).Column(0)
new Label()
.Text("This Label is in Row 1 Column 1")
.Row(1).Column(1)
new Label()
.Text("This Label is in Row 1 Column 2")
.Row(1).Column(2)
}
}
```
--------------------------------
### Initialize CommunityToolkit.Maui with Options
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/options
Configure CommunityToolkit.Maui with custom options during application startup. This is the primary method for setting global toolkit behaviors.
```csharp
var builder = MauiApp.CreateBuilder();
builder.UseMauiCommunityToolkit(options =>
{
options.SetShouldSuppressExceptionsInConverters(false);
options.SetShouldSuppressExceptionsInBehaviors(false);
options.SetShouldSuppressExceptionsInAnimations(false);
})
```
--------------------------------
### Presenting a Popup with IPopupService
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/views/popup-service
Instantiate and present a popup using the IPopupService. Requires resolving the service and passing the current navigation implementation.
```csharp
public class MyViewModel : INotifyPropertyChanged
{
private readonly IPopupService popupService;
public MyViewModel(IPopupService popupService)
{
this.popupService = popupService;
}
public void DisplayPopup()
{
this.popupService.ShowPopup(Shell.Current);
}
}
```
--------------------------------
### Registering the Badge Service in MauiProgram
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/essentials/badge
Register the default IBadge implementation as a singleton within your MauiProgram.cs file to enable dependency injection.
```csharp
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp()
.UseMauiCommunityToolkit();
builder.Services.AddSingleton(Badge.Default);
return builder.Build();
}
}
```
--------------------------------
### Using MultiConverter in C#
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/converters/multi-converter
Shows how to instantiate and configure the MultiConverter, TextCaseConverter, IsEqualConverter, and MultiConverterParameter in C# code for data binding.
```C#
class MultiConverterPage : ContentPage
{
public MultiConverterPage()
{
var label = new Label { Text = "Well done you guessed the magic word!" };
var converter = new MultiConverter
{
new TextCaseConverter(),
new IsEqualConverter()
};
var parameters = new List
{
new MultiConverterParameter { ConverterType = typeof(TextCaseConverter), Value = TextCaseType.Upper },
new MultiConverterParameter { ConverterType = typeof(IsEqualConverter), Value = "MAUI" },
};
label.SetBinding(
Label.IsVisibleProperty,
new Binding(
static (ViewModels vm) => vm.EnteredName,
converter: converter,
converterParameter: parameters));
Content = label;
}
}
```
--------------------------------
### DrawingLineStartedEventArgs
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/views/drawingview
Event argument which contains the last drawing point when a line drawing starts.
```APIDOC
### DrawingLineStartedEventArgs
Event argument which contains last drawing point.
#### Properties
##### Point
- **Type**: `PointF`
- **Description**: Last drawing point.
```
--------------------------------
### Use SelectedItemEventArgsConverter in C#
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/converters/selected-item-eventargs-converter
This C# example demonstrates how to instantiate and use the SelectedItemEventArgsConverter with an EventToCommandBehavior for a ListView.
```C#
class SelectedItemEventArgsConverterPage : ContentPage
{
public SelectedItemEventArgsConverterPage()
{
var behavior = new EventToCommandBehavior
{
EventName = nameof(ListView.ItemSelected),
EventArgsConverter = new SelectedItemEventArgsConverter()
};
behavior.SetBinding(EventToCommandBehavior.CommandProperty, static (ViewModel vm) => vm.ItemSelectedCommand);
var listView = new ListView
{
HasUnevenRows = true
};
listView.SetBinding(ListView.ItemsSource, static (ViewModel vm) => vm.Items);
listView.Behaviors.Add(behavior);
Content = listView;
}
}
```
--------------------------------
### Start Video Recording with Custom Stream
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/views/camera-view
This C# method demonstrates recording a video to a custom FileStream. Ensure a clean stream is provided. The recording is stopped after a delay, and the file is saved.
```C#
async void StartCameraRecordingWithCustomStream(object? sender, EventArgs e)
{
using var threeSecondVideoRecordingStream = new FileStream("recording.mp4", FileMode.Create);
await Camera.StartVideoRecording(threeSecondVideoRecordingStream, CancellationToken.None);
await Task.Delay(TimeSpan.FromSeconds(3));
await Camera.StopVideoRecording(CancellationToken.None);
await FileSaver.SaveAsync("recording.mp4", threeSecondVideoRecordingStream);
}
```
--------------------------------
### Injecting and Using the IBadge Service
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/essentials/badge
Inject the IBadge service into your ContentPage constructor and use it to set badge counts.
```csharp
public partial class MainPage : ContentPage
{
private readonly IBadge badge;
public MainPage(IBadge badge)
{
InitializeComponent();
this.badge = badge;
}
public void SetCount(uint value)
{
badge.SetCount(value);
}
}
```
--------------------------------
### FuncConverter Example
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/markup/converters/func-converter
Defines a type-safe converter for incoming values only. Use when you only need to convert from source to destination.
```csharp
var converter = new FuncConverter(
convert: (time) => time.TotalSeconds,
convertBack: (value) => TimeSpan.FromSeconds((double)value));
```
--------------------------------
### Use ColorToPercentBlackKeyConverter in C#
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/converters/color-to-percent-black-key-converter
Shows how to instantiate and use the ColorToPercentBlackKeyConverter in C# by creating a Binding with the converter.
```C#
class ColorToPercentBlackKeyConverterPage : ContentPage
{
public ColorToPercentBlackKeyConverterPage()
{
var label = new Label();
label.SetBinding(
Label.TextProperty,
new Binding(
static (ViewModel vm) => vm.MyFavoriteColor,
converter: new ColorToPercentBlackKeyConverter()));
Content = new VerticalStackLayout
{
Children =
{
new Label { Text = "The key component is:" },
label
}
};
}
}
```
--------------------------------
### Set Vertical Text Alignment to Start
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/markup/extensions/text-alignment-extensions
Use the `TextTop()` extension method to set the `VerticalTextAlignment` property of a Label to `TextAlignment.Start`.
```csharp
new Label().TextTop()
```
--------------------------------
### SpeechToText Methods
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/essentials/speech-to-text
Provides methods to control the Speech to Text service, such as requesting permissions, starting, and stopping the listening process.
```APIDOC
## RequestPermissions
### Description
Asks for permission to use the Speech to Text service.
### Method
(Not specified, likely a method call)
### Endpoint
(Not applicable for SDK methods)
## StartListenAsync
### Description
Starts the SpeechToText service for real-time speech recognition. Results are surfaced via `RecognitionResultUpdated` and `RecognitionResultCompleted` events.
### Method
(Not specified, likely a method call)
### Endpoint
(Not applicable for SDK methods)
## StopListenAsync
### Description
Stops the SpeechToText service. Final speech recognition results will be surfaced via the `RecognitionResultCompleted` event.
### Method
(Not specified, likely a method call)
### Endpoint
(Not applicable for SDK methods)
```
--------------------------------
### Initialize .NET MAUI Community Toolkit Camera
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/get-started?tabs=CommunityToolkitMaui
Add the using statement and call the UseMauiCommunityToolkitCamera extension method on MauiAppBuilder to enable camera functionality.
```csharp
using CommunityToolkit.Maui;
```
```csharp
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp()
.UseMauiCommunityToolkitCamera()
```
--------------------------------
### Set Font to Italic
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/markup/extensions/element-extensions
The Italic method sets FontAttributes to FontAttributes.Italic on an IFontElement. This example sets the button font to italic.
```csharp
new Button().Italic()
```
--------------------------------
### Initialize CommunityToolkit.Maui.Markup in MauiProgram.cs
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/get-started?tabs=CommunityToolkitMaui
Call the UseMauiCommunityToolkitMarkup method on the MauiAppBuilder when bootstrapping your application in MauiProgram.cs.
```csharp
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp()
.UseMauiCommunityToolkitMarkup()
```
--------------------------------
### Set Font Size for an Element
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/markup/extensions/element-extensions
The FontSize method sets the FontSize property on an IFontElement. Example sets the FontSize to 12.
```csharp
new Button().FontSize(12);
```
--------------------------------
### Create UniformItemsLayout in C#
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/layouts/uniformitemslayout
Shows how to instantiate and configure UniformItemsLayout programmatically in C#.
```C#
using CommunityToolkit.Maui.Views;
var page = new ContentPage
{
Content = new UniformItemsLayout
{
Children =
{
new BoxView { HeightRequest = 25, WidthRequest = 25, BackgroundColor = Colors.Blue },
new BoxView { HeightRequest = 25, WidthRequest = 25, BackgroundColor = Colors.Yellow },
new BoxView { HeightRequest = 25, WidthRequest = 25, BackgroundColor = Colors.Red },
new BoxView { HeightRequest = 25, WidthRequest = 25, BackgroundColor = Colors.Black }
}
}
};
```
--------------------------------
### Use SelectedItemEventArgsConverter in XAML
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/converters/selected-item-eventargs-converter
This example shows how to declare and use the SelectedItemEventArgsConverter within XAML, typically for binding events to commands.
```XAML
```
--------------------------------
### Save File with Progress Reporting
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/essentials/file-saver
For larger files, this example shows how to monitor the saving progress. It utilizes a Progress to update a ProgressBar as the file is being saved, providing visual feedback to the user.
```csharp
async Task SaveFile(CancellationToken cancellationToken)
{
using var stream = new MemoryStream(Encoding.Default.GetBytes("Hello from the Community Toolkit!"));
var saverProgress = new Progress(percentage => ProgressBar.Value = percentage);
var fileSaverResult = await FileSaver.Default.SaveAsync("test.txt", stream, saverProgress, cancellationToken);
if (fileSaverResult.IsSuccessful)
{
await Toast.Make($"The file was saved successfully to location: {fileSaverResult.FilePath}").Show(cancellationToken);
}
else
{
await Toast.Make($"The file was not saved successfully with error: {fileSaverResult.Exception.Message}").Show(cancellationToken);
}
}
```
--------------------------------
### Use EnumToBoolConverter in C#
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/converters/enum-to-bool-converter
Implement the EnumToBoolConverter in C# code-behind. This example makes a Label visible when the selected platform is Tizen.
```csharp
class EnumToBoolConverterPage : ContentPage
{
public EnumToBoolConverterPage()
{
var picker = new Picker();
picker.SetBinding(Picker.ItemsSourceProperty, static (ViewModel vm) => vm.Platforms);
picker.SetBinding(Picker.SelectedItemProperty, static (ViewModel vm) => vm.SelectedPlatform);
var label = new Label
{
Text = "I am visible when the Picker value is Tizen."
};
label.SetBinding(
Label.IsVisibleProperty,
new Binding(
static (ViewModel vm) => vm.SelectedPlatform,
converter: new EnumToBoolConverter(),
converterParameter: MyDevicePlatform.Tizen));
Content = new VerticalStackLayout
{
Children = { picker, label }
};
}
}
```
--------------------------------
### Configure BoolToObjectConverter with Default Return Values (C#)
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/options
This C# example shows how to instantiate and configure a BoolToObjectConverter, setting the objects for true and false states, and defining default return values for both Convert and ConvertBack operations. This provides a programmatic way to handle converter exceptions.
```csharp
var boolToColorBrushConverter = new BoolToObjectConverter
{
TrueObject = new SolidColorBrush(Colors.Green),
FalseObject = new SolidColorBrush(Colors.Red),
DefaultConvertReturnValue = new SolidColorBrush(Colors.Red),
DefaultConvertBackReturnValue = false
};
```
--------------------------------
### Using AnimationBehavior in XAML
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/behaviors/animation-behavior
Apply the AnimationBehavior to a Label in XAML to animate it on tap. This example uses FadeAnimation to change opacity.
```XAML
```
--------------------------------
### Using CompareConverter in C#
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/converters/compare-converter
Illustrates how to instantiate and use the CompareConverter directly in C# code. This is useful for dynamic scenarios or when XAML is not preferred.
```C#
class CompareConverterPage : ContentPage
{
public CompareConverterPage()
{
var label = new Label
{
Text = "The background of this label will be green if the value entered is less than 50, and red otherwise."
};
label.SetBinding(
Label.BackgroundColorProperty,
new Binding(
static (ViewModel vm) => vm.MyValue,
converter: new CompareConverter
{
ComparisonOperator = OperatorType.Smaller,
ComparingValue = 50,
TrueObject = Colors.LightGreen,
FalseObject = Colors.PaleVioletRed
}));
Content = label;
}
}
```
--------------------------------
### Add Toolkit Namespace to XAML Page
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/behaviors/icon-tint-color-behavior
This example shows how to integrate the toolkit namespace into an existing XAML page structure.
```XAML
```
--------------------------------
### Set Label Horizontal Text Alignment to Start
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/markup/extensions/text-alignment-extensions
Use the TextStart extension method to set the HorizontalTextAlignment property of a Label to TextAlignment.Start.
```csharp
new Label().TextStart()
```
--------------------------------
### Enable .NET MAUI Community Toolkit
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/get-started?tabs=CommunityToolkitMaui
Add the `UseMauiCommunityToolkit()` extension method to your MauiProgram.cs file to enable the toolkit.
```csharp
var builder = MauiApp.CreateBuilder();
builder.UseMauiApp();
builder.UseMauiCommunityToolkit();
```
--------------------------------
### Set Text Color for an Element
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/markup/extensions/element-extensions
The TextColor method sets the TextColor property on an ITextStyle element. Example sets the TextColor to Colors.Green.
```csharp
new Button().TextColor(Colors.Green);
```
--------------------------------
### Presenting a Popup with Data using IPopupService
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/views/popup-service
Use the `IPopupService` to show a Popup and pass data to its ViewModel. The `ShowPopupAsync` method accepts a `shellParameters` dictionary, which is then processed by the ViewModel implementing `IQueryAttributable`.
```csharp
public class MyViewModel : INotifyPropertyChanged
{
private readonly IPopupService popupService;
public MyViewModel(IPopupService popupService)
{
this.popupService = popupService;
}
public async Task DisplayPopup()
{
var queryAttributes = new Dictionary
{
[nameof(NamePopupViewModel.Name)] = "Shaun"
};
await this.popupService.ShowPopupAsync(
Shell.Current,
options: PopupOptions.Empty,
shellParameters: queryAttributes);
}
}
```
--------------------------------
### Initialize .NET MAUI Community Toolkit MediaElement
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/get-started?tabs=CommunityToolkitMaui
Add the using statement and call the UseMauiCommunityToolkitMediaElement extension method on MauiAppBuilder. Configure foreground service for Android if needed for background playback or rich media notifications.
```csharp
using CommunityToolkit.Maui;
```
```csharp
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp()
.UseMauiCommunityToolkitMediaElement(enableForegroundService: true);
```
--------------------------------
### Set Font to Bold
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/markup/extensions/element-extensions
Use the Bold method to set FontAttributes to FontAttributes.Bold on an IFontElement. This example sets the button font to bold.
```csharp
new Button().Bold()
```
--------------------------------
### AbsoluteLayout with Extensions
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/markup/extensions/absolute-layout-extensions
Demonstrates the usage of LayoutBounds and LayoutFlags extension methods to position and size Views within an AbsoluteLayout. This example showcases various combinations of proportional and absolute positioning and sizing.
```csharp
using CommunityToolkit.Maui.Markup;
using Microsoft.Maui.Layouts;
public class AbsoluteLayoutSamplePage : ContentPage
{
public AbsoluteLayoutSamplePage()
{
Content = new AbsoluteLayout
{
Children =
{
new BoxView
{
Color = Colors.Blue,
}.LayoutFlags(AbsoluteLayoutFlags.PositionProportional)
.LayoutBounds(0.5, 0, 100, 25),
new BoxView
{
Color = Colors.Green,
WidthRequest = 25,
HeightRequest = 100,
}.LayoutFlags(AbsoluteLayoutFlags.PositionProportional)
.LayoutBounds(0, 0.5),
new BoxView
{
Color = Colors.Pink,
}.LayoutFlags(AbsoluteLayoutFlags.PositionProportional, AbsoluteLayoutFlags.SizeProportional)
.LayoutBounds(0, 0.5, 0.25, 0.25),
new BoxView
{
Color = Colors.Red,
WidthRequest = 25,
HeightRequest = 100,
}.LayoutFlags(AbsoluteLayoutFlags.PositionProportional)
.LayoutBounds(new Point(1, 0.5)),
new BoxView
{
Color = Colors.Grey,
}.LayoutFlags(AbsoluteLayoutFlags.PositionProportional)
.LayoutBounds(new Point(0.5, 1), new Size(100, 25)),
new BoxView
{
Color = Colors.Tan,
}.LayoutFlags(AbsoluteLayoutFlags.All)
.LayoutBounds(new Rect(0.5, 0.5, 1d / 3d, 1d / 3d))
}
};
}
}
```
--------------------------------
### Set Image IsOpaque
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/markup/extensions/image-extensions
Use the IsOpaque method to set the IsOpaque property on an IImage element. This example sets IsOpaque to true.
```csharp
new Image().IsOpaque(true);
```
--------------------------------
### Using ColorToPercentYellowConverter in C#
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/converters/color-to-percent-yellow-converter
Shows how to instantiate and use the ColorToPercentYellowConverter in C# code-behind by creating a Binding with the converter.
```C#
class ColorToPercentYellowConverterPage : ContentPage
{
public ColorToPercentYellowConverterPage()
{
var label = new Label();
label.SetBinding(
Label.TextProperty,
new Binding(
static (ViewModel vm) => vm.MyFavoriteColor,
converter: new ColorToPercentYellowConverter()));
Content = new VerticalStackLayout
{
Children =
{
new Label { Text = "The yellow component is:" },
label
}
};
}
}
```
--------------------------------
### Set Image Aspect
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/markup/extensions/image-extensions
Use the Aspect method to set the Aspect property on an IImage element. This example sets the aspect to Aspect.AspectFill.
```csharp
new Image().Aspect(Aspect.AspectFill);
```
--------------------------------
### Create a Grid with Labeled Entry using C# Markup
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/markup/markup
Builds a Grid with a Label and an Entry, demonstrating fluent API for row/column definitions, data binding, and styling. Uses enums for row and column naming.
```csharp
using CommunityToolkit.Maui.Markup;
using static CommunityToolkit.Maui.Markup.GridRowsColumns;
class SampleContentPage : ContentPage
{
public SampleContentPage()
{
Content = new Grid
{
RowDefinitions = Rows.Define(
(Row.TextEntry, 36)),
ColumnDefinitions = Columns.Define(
(Column.Description, Star),
(Column.Input, Stars(2))),
Children =
{
new Label()
.Text("Code:")
.Row(Row.TextEntry).Column(Column.Description),
new Entry
{
Keyboard = Keyboard.Numeric,
}.Row(Row.TextEntry).Column(Column.Input)
.BackgroundColor(Colors.AliceBlue)
.FontSize(15)
.Placeholder("Enter number")
.TextColor(Colors.Black)
.Height(44)
.Margin(5, 5)
.Bind(Entry.TextProperty, static (ViewModel vm) => vm.RegistrationCode, static (ViewModel vm, string text) => vm.RegistrationCode = text)
}
};
}
enum Row { TextEntry }
enum Column { Description, Input }
}
```
--------------------------------
### Use SelectedItemEventArgsConverter with C# Markup
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/converters/selected-item-eventargs-converter
This C# Markup example shows a concise way to use the SelectedItemEventArgsConverter with EventToCommandBehavior and data binding.
```C#
using CommunityToolkit.Maui.Markup;
class SelectedItemEventArgsConverterPage : ContentPage
{
public SelectedItemEventArgsConverterPage()
{
Content = new ListView
{
HasUnevenRows = true
}
.Bind(
ListView.ItemsSourceProperty,
static (ViewModel vm) => vm.Items)
.Behaviors(
new EventToCommandBehavior
{
EventName = nameof(ListView.ItemSelected),
EventArgsConverter = new SelectedItemEventArgsConverter()
}
.Bind(
EventToCommandBehavior.CommandProperty,
static (ViewModel vm) => vm.ItemTappedCommand));
}
}
```
--------------------------------
### Using AnimationBehavior with C# Markup
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/behaviors/animation-behavior
Utilize the CommunityToolkit.Maui.Markup package for a concise C# implementation of AnimationBehavior. This example animates a Label on tap.
```C#
using CommunityToolkit.Maui.Markup;
class AnimationBehaviorPage : ContentPage
{
public AnimationBehaviorPage()
{
Content = new Label()
.Text("Click this label")
.Behaviors(new AnimationBehavior
{
AnimateOnTap = true,
AnimationType = new FadeAnimation
{
Opacity = 0.5
}
});
}
}
```
--------------------------------
### Initialize CommunityToolkit.Maui in MauiProgram.cs
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/get-started?tabs=CommunityToolkitMaui
Call the UseMauiCommunityToolkit method on the MauiAppBuilder when bootstrapping your application in MauiProgram.cs.
```csharp
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp()
.UseMauiCommunityToolkit()
```
--------------------------------
### C# FadeAnimation Example
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/animations/fade-animation
This snippet demonstrates how to use the FadeAnimation in C# to animate the opacity of a Label. Ensure the FadeAnimation class is accessible.
```csharp
public async void Animate()
{
var label = new Label();
var fadeAnimation = new FadeAnimation();
await fadeAnimation.Animate(label);
}
```
--------------------------------
### Configure .NET MAUI Community Toolkit Options
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/get-started?tabs=CommunityToolkitMaui
Use the `UseMauiCommunityToolkit` overload with an options lambda to configure advanced settings like exception suppression for converters, behaviors, and animations.
```csharp
builder.UseMauiCommunityToolkit(options =>
{
options.SetShouldSuppressExceptionsInConverters(false);
options.SetShouldSuppressExceptionsInBehaviors(false);
options.SetShouldSuppressExceptionsInAnimations(false);
});
```
--------------------------------
### Basic CameraView XAML Integration
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/views/camera-view
Embed the CameraView within your XAML layout. This example places the CameraView to span all columns and rows in a Grid.
```xaml
```
--------------------------------
### Fluent Style Configuration with Add Methods
Source: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/markup/extensions/style
Configure a Label's style fluently using Add methods for theme bindings, property setters, behaviors, and triggers.
```csharp
new Label
{
Style = new Style