### Complete Mac Catalyst Info.plist Example
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/views/camera-view.md
A comprehensive example of an Info.plist file for Mac Catalyst, including camera and microphone usage descriptions.
```xml
UIDeviceFamily
1
2
UIRequiredDeviceCapabilities
arm64
UISupportedInterfaceOrientations
UIInterfaceOrientationPortrait
UIInterfaceOrientationLandscapeLeft
UIInterfaceOrientationLandscapeRight
UISupportedInterfaceOrientations~ipad
UIInterfaceOrientationPortrait
UIInterfaceOrientationPortraitUpsideDown
UIInterfaceOrientationLandscapeLeft
UIInterfaceOrientationLandscapeRight
XSAppIconAssets
Assets.xcassets/appicon.appiconset
NSCameraUsageDescription
PROVIDE YOUR REASON HERE
NSMicrophoneUsageDescription
PROVIDE YOUR REASON HERE
```
--------------------------------
### Start Camera Preview using C# Method
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/views/camera-view.md
This C# code demonstrates how to programmatically start the camera preview using the StartCameraPreview method of the CameraView. It includes basic error handling and a cancellation token with a timeout.
```csharp
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);
}
}
```
--------------------------------
### Initialize CameraHelper and Start Capture
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Helpers/CameraHelper.md
Creates a Camera Helper instance and starts capturing video frames from an available frame source. Handles initialization success or failure and subscribes to frame arrival events.
```csharp
// Creates a Camera Helper and gets video frames from an available frame source.
using CommunityToolkit.WinUI.Helpers.CameraHelper;
CameraHelper _cameraHelper = new CameraHelper();
var result = await _cameraHelper.InitializeAndStartCaptureAsync();
// Camera Initialization and Capture failed for some reason
if(result != CameraHelperResult.Success)
{
// get error information
var errorMessage = result.ToString();
}
else
{
// Subscribe to get frames as they arrive
_cameraHelper.FrameArrived += CameraHelper_FrameArrived;
}
private void CameraHelper_FrameArrived(object sender, FrameEventArgs e)
{
// Gets the current video frame
VideoFrame currentVideoFrame = e.VideoFrame;
// Gets the software bitmap image
SoftwareBitmap softwareBitmap = currentVideoFrame.SoftwareBitmap;
}
```
--------------------------------
### CameraHelper with Specific Frame Source Group
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Helpers/CameraHelper.md
This example shows how to get available frame source groups, select one, and then initialize the CameraHelper with that specific group. It also demonstrates setting a different frame source format.
```APIDOC
## CameraHelper with Specific Frame Source Group
### Description
Demonstrates how to retrieve all available camera frame source groups, select a preferred one, and initialize the CameraHelper with it. It also includes an optional step to set a specific frame format for the preview stream.
### Method
`GetFrameSourceGroupsAsync()`, `InitializeAndStartCaptureAsync()`, `PreviewFrameSource.SetFormatAsync()`
### Parameters
`GetFrameSourceGroupsAsync()`: None
`InitializeAndStartCaptureAsync()`: None
`PreviewFrameSource.SetFormatAsync(MediaFrameFormat format)`: The desired `MediaFrameFormat` to set.
### Request Example
```csharp
using CommunityToolkit.WinUI.Helpers.CameraHelper;
using System.Linq;
var availableFrameSourceGroups = await CameraHelper.GetFrameSourceGroupsAsync();
if(availableFrameSourceGroups != null)
{
CameraHelper cameraHelper = new CameraHelper() { FrameSourceGroup = availableFrameSourceGroups.FirstOrDefault() };
var result = await cameraHelper.InitializeAndStartCaptureAsync();
if(result == CameraHelperResult.Success)
{
cameraHelper.FrameArrived += CameraHelper_FrameArrived;
var newFormat = cameraHelper.FrameFormatsAvailable.Find((format) => format.VideoFormat.Width == 640);
if (newFormat != null)
{
await cameraHelper.PreviewFrameSource.SetFormatAsync(newFormat);
}
}
}
```
### Response
#### Success Response (CameraHelperResult.Success)
Indicates successful initialization and capture start with the selected frame source group and format.
#### Error Response (Other CameraHelperResult values)
Indicates a failure during initialization or capture. The specific error can be obtained from the `result.ToString()`.
```
--------------------------------
### Settings Page Example Code-Behind
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/SettingsControls/SettingsExpander.md
Provides the C# code-behind for the Settings page example, initializing the page and its data context.
```csharp
public sealed partial class SettingsPageExample : Page
{
public SettingsPageExample()
{
this.InitializeComponent();
}
}
```
--------------------------------
### Set HorizontalAlignment to Start using Start Extension
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/markup/extensions/view-extensions.md
Use the `Start()` extension method to set the `HorizontalOptions` property to `LayoutOptions.Start`.
```csharp
new Label().Start()
```
--------------------------------
### CameraView XAML Setup for Video Recording
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/views/camera-view.md
This XAML sets up the CameraView and includes buttons to start and stop video recording using commands. Ensure the `StartVideoRecordingCommand` and `StopVideoRecordingCommand` are bound to the CameraView.
```xaml
```
--------------------------------
### Start Animation Activity Sample XAML
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Behaviors/AnimationSet.md
This XAML file defines the Start Animation Activity sample, showcasing how to use behaviors to initiate animations.
```xaml
```
--------------------------------
### PropertySizer Code-Behind for NavigationView
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Sizers/PropertySizer.md
This C# code-behind file provides the necessary setup for the PropertySizer and NavigationView example. It initializes the page and ensures the data context is correctly set.
```csharp
namespace CommunityToolkit.WinUI.Sample.Views.Sizers
{
public sealed partial class PropertySizerNavigationViewPage : Page
{
public PropertySizerNavigationViewPage()
{
this.InitializeComponent();
}
}
}
```
--------------------------------
### Start Animation Activity Sample Code Behind
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Behaviors/AnimationSet.md
This C# code-behind file is associated with the Start Animation Activity sample, containing the necessary code-behind logic.
```csharp
// This is a placeholder for the actual C# code from the source file
// The content of StartAnimationActivitySample.xaml.cs is not provided in the prompt
```
--------------------------------
### Using ByteArrayToImageSourceConverter with CommunityToolkit.Maui.Markup
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/converters/byte-array-to-image-source-converter.md
This C# markup example showcases a more concise way to use the ByteArrayToImageSourceConverter with the CommunityToolkit.Maui.Markup package. It utilizes extension methods for binding to simplify the setup of the Image control's Source property.
```csharp
using CommunityToolkit.Maui.Markup;
class ByteArrayToImageSourceConverterPage : ContentPage
{
public ByteArrayToImageSourceConverterPage()
{
Content = new Image()
.Bind(
Image.SourceProperty,
static (ViewModel vm) => vm.DotNetBotImageByteArray,
mode: BindingMode.OneWay,
converter: new ByteArrayToImageSourceConverter());
}
}
```
--------------------------------
### MauiProgram.cs Example
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/markup/dotnet-hot-reload.md
This example shows how to add the ICommunityToolkitHotReloadHandler implementation to the Dependency Injection container within MauiProgram.cs. Modify this code to fit your specific application architecture.
```csharp
public class MauiProgram
{
public static MauiApp CreateMauiApp()
{
// ...
// Additional code ommitted for brevity
// ...
// Register C# Hot Reload Handler
builder.Services.AddSingleton();
// ...
// Additional code ommitted for brevity
// ...
}
}
```
--------------------------------
### CameraPreview Basic C# Usage
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/CameraPreview/index.md
Demonstrates starting the camera preview, handling preview failures, and accessing arrived frames.
```csharp
CameraPreviewControl.PreviewFailed += CameraPreviewControl_PreviewFailed;
await CameraPreviewControl.StartAsync();
CameraPreviewControl.CameraHelper.FrameArrived += CameraPreviewControl_FrameArrived;
private void CameraPreviewControl_FrameArrived(object sender, FrameEventArgs e)
{
var videoFrame = e.VideoFrame;
var softwareBitmap = videoFrame.SoftwareBitmap;
}
private void CameraPreviewControl_PreviewFailed(object sender, PreviewFailedEventArgs e)
{
var errorMessage = e.Error;
}
```
--------------------------------
### DockPanel Layout Example
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Primitives/DockPanel.md
Demonstrates how to use the DockPanel to arrange child elements with different docking options.
```xaml
```
--------------------------------
### BasedOn Example
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/markup/extensions/style.md
Example of creating a new Label style that is based on a previously defined red text Label style.
```csharp
new VerticalStackLayout
{
Children =
{
new Label
{
Style = new Style(Label.TextColorProperty, Colors.Red)
}.Assign(out Label redTextLabel),
new Label
{
Style = new Style().BasedOn(redTextLabel.Style);
}
}
};
```
--------------------------------
### Using ColorToPercentBlackKeyConverter with C# Markup
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/converters/color-to-percent-black-key-converter.md
This example shows a more concise way to use the ColorToPercentBlackKeyConverter with the CommunityToolkit.Maui.Markup package in C#.
```csharp
using CommunityToolkit.Maui.Markup;
class ColorToPercentBlackKeyConverterPage : ContentPage
{
public ColorToPercentBlackKeyConverterPage()
{
Content = new VerticalStackLayout
{
Children =
{
new Label()
.Text("The key component is:"),
new Label()
.Bind(
Label.TextProperty,
static (ViewModel vm) => vm.MyFavoriteColor,
converter: new ColorToPercentBlackKeyConverter())
}
};
}
}
```
--------------------------------
### Use ColorToPercentCyanConverter with C# Markup
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/converters/color-to-percent-cyan-converter.md
This example utilizes the CommunityToolkit.Maui.Markup package for a more concise C# implementation of the ColorToPercentCyanConverter.
```csharp
using CommunityToolkit.Maui.Markup;
class ColorToPercentCyanConverterPage : ContentPage
{
public ColorToPercentCyanConverterPage()
{
Content = new VerticalStackLayout
{
Children =
{
new Label()
.Text("The cyan component is:"),
new Label()
.Bind(
Label.TextProperty,
static (ViewModel vm) => vm.MyFavoriteColor,
converter: new ColorToPercentCyanConverter())
}
};
}
}
```
--------------------------------
### Using ColorToPercentYellowConverter with C# Markup
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/converters/color-to-percent-yellow-converter.md
This C# Markup example utilizes the CommunityToolkit.Maui.Markup package for a more concise way to use the ColorToPercentYellowConverter.
```csharp
using CommunityToolkit.Maui.Markup;
class ColorToPercentYellowConverterPage : ContentPage
{
public ColorToPercentYellowConverterPage()
{
Content = new VerticalStackLayout
{
Children =
{
new Label()
.Text("The yellow component is:"),
new Label()
.Bind(
Label.TextProperty,
static (ViewModel vm) => vm.MyFavoriteColor,
converter: new ColorToPercentYellowConverter())
}
};
}
}
```
--------------------------------
### CompareStateTrigger XAML Example
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Triggers/index.md
Demonstrates how to use the CompareStateTrigger in XAML to enable a state based on value comparison.
```xaml
```
--------------------------------
### AlternateColor C# Example
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Extensions/ListViewExtensions.md
This C# code accompanies the XAML example for AlternateColor, likely containing the ViewModel or data binding setup.
```csharp
public sealed partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
MainViewModel = new MainViewModel();
}
public MainViewModel MainViewModel { get; }
}
public class MainViewModel
{
public ObservableCollection Items { get; }
public MainViewModel()
{
Items = new ObservableCollection
{
"Item 1",
"Item 2",
"Item 3",
"Item 4",
"Item 5",
"Item 6",
"Item 7",
"Item 8"
};
}
}
```
--------------------------------
### UriValidationBehavior C# Markup Example
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/behaviors/uri-validation-behavior.md
This C# Markup example provides a concise way to use the UriValidationBehavior. It leverages the CommunityToolkit.Maui.Markup extension to chain behavior configuration directly onto the Entry control, simplifying the setup for styling and validation rules.
```csharp
using CommunityToolkit.Maui.Markup;
class UriValidationBehaviorPage : ContentPage
{
public UriValidationBehaviorPage()
{
Content = new Entry()
.Behaviors(new UriValidationBehavior
{
InvalidStyle = new Style(Entry.TextColorProperty, Colors.Red),
ValidStyle = new Style(Entry.TextColorProperty, Colors.Green),
Flags = ValidationFlags.ValidateOnValueChanged,
UriKind = UriKind.Absolute
});
}
}
```
--------------------------------
### Using ColorToBlackOrWhiteConverter with C# Markup
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/converters/color-to-black-or-white-converter.md
This example utilizes the CommunityToolkit.Maui.Markup package for a more concise way to apply the ColorToBlackOrWhiteConverter in C# code.
```csharp
using CommunityToolkit.Maui.Markup;
class ColorToBlackOrWhiteConverterPage : ContentPage
{
public ColorToBlackOrWhiteConverterPage()
{
Content = new Label { Text = "The Text is showing in monochrome" }
.Bind(
Label.TextColorProperty,
static (ViewModel vm) => vm.AppTextColor,
converter: new ColorToBlackOrWhiteConverter());
}
}
```
--------------------------------
### Get Video Frames from Specific Media Frame Source Group
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Helpers/CameraHelper.md
Demonstrates using Camera Helper to get video frames from a specific media frame source group. It initializes the helper, starts capture, and optionally sets a different frame source format.
```csharp
using CommunityToolkit.WinUI.Helpers.CameraHelper;
var availableFrameSourceGroups = await CameraHelper.GetFrameSourceGroupsAsync();
if(availableFrameSourceGroups != null)
{
CameraHelper cameraHelper = new CameraHelper() { FrameSourceGroup = availableFrameSourceGroups.FirstOrDefault() };
var result = await cameraHelper.InitializeAndStartCaptureAsync();
// Camera Initialization succeeded
if(result == CameraHelperResult.Success)
{
// Subscribe to get frames as they arrive
cameraHelper.FrameArrived += CameraHelper_FrameArrived;
// Optionally set a different frame source format
var newFormat = cameraHelper.FrameFormatsAvailable.Find((format) => format.VideoFormat.Width == 640);
if (newFormat != null)
{
await cameraHelper.PreviewFrameSource.SetFormatAsync(newFormat);
}
}
}
```
--------------------------------
### Configure Services with IServiceProvider
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/mvvm/Ioc.md
Sets up the IServiceProvider by registering services like IFilesService, ISettingsService, etc., typically done at application startup. This allows for easy resolution of these services later.
```csharp
public sealed partial class App : Application
{
public App()
{
Services = ConfigureServices();
this.InitializeComponent();
}
///
/// Gets the current instance in use
///
public new static App Current => (App)Application.Current;
///
/// 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.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
return services.BuildServiceProvider();
}
}
```
--------------------------------
### ConstrainedBox Scaling Example
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Primitives/ConstrainedBox.md
Demonstrates using ScaleX and ScaleY to maintain a 'safe' margin around content, proportional to the viewport.
```xaml
```
--------------------------------
### Using ColorToPercentMagentaConverter with C# Markup
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/converters/color-to-percent-magenta-converter.md
This C# markup example utilizes the CommunityToolkit.Maui.Markup package for a more concise way to use the ColorToPercentMagentaConverter.
```csharp
using CommunityToolkit.Maui.Markup;
class ColorToPercentMagentaConverterPage : ContentPage
{
public ColorToPercentMagentaConverterPage()
{
Content = new VerticalStackLayout
{
Children =
{
new Label()
.Text("The magenta component is:"),
new Label()
.Bind(
Label.TextProperty,
static (ViewModel vm) => vm.MyFavoriteColor,
converter: new ColorToPercentMagentaConverter())
}
};
}
}
```
--------------------------------
### Observable Property Setup
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/mvvm/generators/Overview.md
Compare the traditional way of setting up an observable property with the simplified approach using the [ObservableProperty] attribute.
```csharp
private string? name;
public string? Name
{
get => name;
set => SetProperty(ref name, value);
}
```
```csharp
[ObservableProperty]
private string? name;
```
--------------------------------
### GridSplitter XAML Definition
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Sizers/GridSplitter.md
Define the GridSplitter control within your XAML layout to enable resizing of grid columns or rows. This example shows a basic setup.
```xaml
```
--------------------------------
### Initialize Style with Single Setter
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/markup/extensions/style.md
Example of initializing Style with a single setter for a Label's text color.
```csharp
new Label
{
Style = new Style(Entry.TextColorProperty, Colors.Red)
}
```
--------------------------------
### Using ColorToCmykStringConverter in C#
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/converters/color-to-cmyk-string-converter.md
This example demonstrates how to instantiate and use the ColorToCmykStringConverter programmatically in C# by creating a Binding with the converter.
```csharp
class ColorToCmykStringConverterPage : ContentPage
{
public ColorToCmykStringConverterPage()
{
var label = new Label();
label.SetBinding(
Label.TextProperty,
new Binding(
static (ViewModel vm) => vm.MyFavoriteColor,
converter: new ColorToCmykStringConverter()));
Content = new VerticalStackLayout
{
Children =
{
new Label { Text = "My favourite Color is:" },
label
}
};
}
}
```
--------------------------------
### Using ColorToHexRgbaStringConverter with C# Markup
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/converters/color-to-hex-rgba-string-converter.md
This C# Markup example demonstrates a more concise way to use the ColorToHexRgbaStringConverter with the CommunityToolkit.Maui.Markup package.
```csharp
using CommunityToolkit.Maui.Markup;
class ColorToHexRgbaStringConverterPage : ContentPage
{
public ColorToHexRgbaStringConverterPage()
{
Content = new VerticalStackLayout
{
Children =
{
new Label()
.Text("My favourite Color is:"),
new Label()
.Bind(
Label.TextProperty,
static (ViewModel vm) => vm.MyFavoriteColor,
converter: new ColorToHexRgbaStringConverter())
}
};
}
}
```
--------------------------------
### Completed Applications Tag for Snackbar Support
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/includes/toast-snackbar-setup.md
An example of a complete `` tag that includes the necessary extensions for Snackbar support.
```xml
```
--------------------------------
### CameraPreview with CameraHelper Initialization
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/CameraPreview/index.md
Shows how to initialize CameraPreview using CameraHelper, selecting a specific frame source group, and handling frame arrival.
```csharp
var availableFrameSourceGroups = await CameraHelper.GetFrameSourceGroupsAsync();
if(availableFrameSourceGroups != null)
{
CameraHelper cameraHelper = new CameraHelper() { FrameSourceGroup = availableFrameSourceGroups.FirstOrDefault() };
_cameraPreviewControl.PreviewFailed += CameraPreviewControl_PreviewFailed;
await _cameraPreviewControl.StartAsync(cameraHelper);
_cameraPreviewControl.CameraHelper.FrameArrived += CameraPreviewControl_FrameArrived;
}
```
--------------------------------
### Configure Service Provider
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/mvvm/PuttingThingsTogether.md
Sets up the application's service provider by configuring services, including registering platform-specific implementations like the SettingsService. This is typically done at application startup.
```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();
```
--------------------------------
### Command Creation
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/mvvm/generators/Overview.md
Illustrates the reduction in boilerplate for creating commands. The first snippet shows the manual setup, while the second uses the [RelayCommand] attribute for a more concise implementation.
```csharp
private void SayHello()
{
Console.WriteLine("Hello");
}
private ICommand? sayHelloCommand;
public ICommand SayHelloCommand => sayHelloCommand ??= new RelayCommand(SayHello);
```
```csharp
[RelayCommand]
private void SayHello()
{
Console.WriteLine("Hello");
}
```
--------------------------------
### CameraHelper Initialization and Frame Capture
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Helpers/CameraHelper.md
This snippet demonstrates how to initialize the CameraHelper, start video capture, and subscribe to frame arrival events. It also shows how to handle potential initialization failures.
```APIDOC
## CameraHelper Initialization and Frame Capture
### Description
Initializes the CameraHelper and starts capturing video frames. Handles success and failure scenarios, and subscribes to the `FrameArrived` event to process incoming frames.
### Method
`InitializeAndStartCaptureAsync()`
### Parameters
None
### Request Example
```csharp
using CommunityToolkit.WinUI.Helpers.CameraHelper;
CameraHelper _cameraHelper = new CameraHelper();
var result = await _cameraHelper.InitializeAndStartCaptureAsync();
if(result != CameraHelperResult.Success)
{
var errorMessage = result.ToString();
}
else
{
_cameraHelper.FrameArrived += CameraHelper_FrameArrived;
}
private void CameraHelper_FrameArrived(object sender, FrameEventArgs e)
{
VideoFrame currentVideoFrame = e.VideoFrame;
SoftwareBitmap softwareBitmap = currentVideoFrame.SoftwareBitmap;
}
```
### Response
#### Success Response (CameraHelperResult.Success)
Indicates that the camera initialization and capture started successfully.
#### Error Response (Other CameraHelperResult values)
Indicates a failure during initialization or capture. The specific error can be obtained from the `result.ToString()`.
```
--------------------------------
### CanCascade Example
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/markup/extensions/style.md
Example of setting the CanCascade property to true for a Label style.
```csharp
new Label
{
Style = new Style(Label.TextColorProperty, Colors.Red).CanCascade(true);
}
```
--------------------------------
### Initialize CommunityToolkit.Maui with Options
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/options.md
Use the UseMauiCommunityToolkit extension method with an options lambda to configure the toolkit's behavior at startup.
```csharp
var builder = MauiApp.CreateBuilder();
builder.UseMauiCommunityToolkit(options =>
{
options.SetShouldSuppressExceptionsInConverters(false);
options.SetShouldSuppressExceptionsInBehaviors(false);
options.SetShouldSuppressExceptionsInAnimations(false);
})
```
--------------------------------
### ImageCropper XAML Setup
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/ImageCropper/index.md
Basic XAML setup for the ImageCropper control. Ensure the correct namespace is included.
```xaml
```
--------------------------------
### Registering Services and Resolving a Logger
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/mvvm/Ioc.md
Demonstrates how to register services like IFilesService, IConsoleService, and IFileLogger, and then resolve an IFileLogger instance using constructor injection.
```csharp
public class FileLogger : IFileLogger
{
private readonly IFilesService FileService;
private readonly IConsoleService ConsoleService;
public FileLogger(
IFilesService fileService,
IConsoleService consoleService)
{
FileService = fileService;
ConsoleService = consoleService;
}
// Methods for the IFileLogger interface here...
}
```
```csharp
///
/// Configures the services for the application.
///
private static IServiceProvider ConfigureServices()
{
var services = new ServiceCollection();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
return services.BuildServiceProvider();
}
// Retrieve a logger service with constructor injection
IFileLogger fileLogger = App.Current.Services.GetService();
```
--------------------------------
### Initialize CommunityToolkit.Maui.Markup
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/get-started.md
Add the using statement to your MauiProgram.cs file. Call the UseMauiCommunityToolkitMarkup method on the MauiAppBuilder when bootstrapping your application.
```csharp
using CommunityToolkit.Maui.Markup;
```
```csharp
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp()
.UseMauiCommunityToolkitMarkup()
```
--------------------------------
### ApplyToDerivedTypes Example
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/markup/extensions/style.md
Example of using ApplyToDerivedTypes to set a Label's text color and apply it to derived Label types.
```csharp
new Label
{
Style = new Style(Label.TextColorProperty, Colors.Red)
.ApplyToDerivedTypes(true);
}
```
--------------------------------
### Speech To Text - Start Listening
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/essentials/speech-to-text.md
Starts the SpeechToText service for real-time speech recognition. Results are surfaced via RecognitionResultUpdated and RecognitionResultCompleted events.
```APIDOC
## Speech To Text - Start Listening
```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);
}
void OnRecognitionTextUpdated(object? sender, SpeechToTextRecognitionResultUpdatedEventArgs args)
{
RecognitionText += args.RecognitionResult;
}
```
```
--------------------------------
### StaggeredLayout C# Sample
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Primitives/StaggeredLayout.md
This C# code demonstrates the setup and usage of the StaggeredLayout. It includes the necessary resource definition for the layout and sample data.
```csharp
public sealed partial class StaggeredLayoutSample : Page
{
public StaggeredLayoutSample()
{
this.InitializeComponent();
this.DataContext = this;
SampleItems = new ObservableCollection(Enumerable.Range(0, 50).Select(i => $"Item {i}"));
}
public ObservableCollection SampleItems { get; }
}
```
--------------------------------
### Grid with Row and Column Definitions and Children
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/markup/extensions/grid-extensions.md
This example demonstrates creating a Grid with specific row and column definitions and populating it with Label children, assigning each to its respective row and column using extension methods.
```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)
}
}
```
--------------------------------
### Get and Use DispatcherQueue
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Extensions/DispatcherQueueExtensions.md
Demonstrates how to get a DispatcherQueue instance for the current thread and use its EnqueueAsync method to execute synchronous or asynchronous delegates, with or without returning a value.
```csharp
DispatcherQueue dispatcherQueue = DispatcherQueue.GetForCurrentThread();
await dispatcherQueue.EnqueueAsync(() =>
{
});
int someValue = await dispatcherQueue.EnqueueAsync(() =>
{
return 42;
});
await dispatcherQueue.EnqueueAsync(async () =>
{
await Task.Delay(100);
});
int someOtherValue = await dispatcherQueue.EnqueueAsync(async () =>
{
await Task.Delay(100);
return 42;
});
```
--------------------------------
### NetworkHelper Sample C#
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Helpers/NetworkHelper.md
This C# code demonstrates how to use the NetworkHelper to get connection information and bind it to UI elements.
```csharp
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.Networking.Connectivity;
using CommunityToolkit.Helpers;
namespace CommunityToolkit.Helpers.Sample
{
public sealed partial class NetworkHelperSamplePage : INotifyPropertyChanged
{
private readonly NetworkHelper _networkHelper;
public string ConnectionType => _networkHelper.ConnectionInformation.ConnectionType.ToString();
public string ConnectivityLevel => _networkHelper.ConnectionInformation.ConnectivityLevel.ToString();
public string ConnectionCost => _networkHelper.ConnectionInformation.ConnectionCost.ToString();
public string SignalStrength => _networkHelper.ConnectionInformation.SignalStrength?.ToString() ?? "N/A";
public string InternetAccess => _networkHelper.ConnectionInformation.InternetAccess.ToString();
public NetworkHelperSamplePage()
{
InitializeComponent();
_networkHelper = new NetworkHelper();
DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
```
--------------------------------
### Invalid Ref Lifetime Example
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/high-performance/Ref.md
This example demonstrates an invalid use of Ref where the referenced value's lifetime is shorter than the Ref instance. Dereferencing the returned ref int can lead to crashes.
```csharp
public static ref int GetDummyReference()
{
int number = 42;
Ref byRef = new Ref(ref number);
return ref byRef.Value;
}
```
--------------------------------
### Initialize CommunityToolkit.Maui
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/get-started.md
Add the using statement to your MauiProgram.cs file. Call the UseMauiCommunityToolkit method on the MauiAppBuilder when bootstrapping your application.
```csharp
using CommunityToolkit.Maui;
```
```csharp
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp()
.UseMauiCommunityToolkit()
```
--------------------------------
### Pick Folder
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/essentials/folder-picker.md
This example demonstrates how to use the FolderPicker to allow users to select a folder and display a toast message with the folder's name and path, or an error message if the operation fails.
```APIDOC
## Pick Folder
```csharp
async Task PickFolder(CancellationToken cancellationToken)
{
var result = await FolderPicker.Default.PickAsync(cancellationToken);
if (result.IsSuccessful)
{
await Toast.Make($
```
--------------------------------
### DrawingLineStartedEventArgs Properties
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/views/DrawingView.md
Event arguments for when a drawing line starts.
```APIDOC
### DrawingLineStartedEventArgs
Event argument which contains the last drawing point.
#### Properties
| Property | Type | Description |
|---|---|---|
| Point | `PointF` | Last drawing point. |
```
--------------------------------
### RegexStateTrigger C# Code-Behind
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Triggers/index.md
The C# code-behind for the RegexStateTrigger XAML example.
```csharp
public sealed partial class RegexStateTriggerSample : Page
{
public RegexStateTriggerSample()
{
this.InitializeComponent();
InputText = "HelloWorld";
}
public string InputText { get; set; }
}
```
--------------------------------
### Start Video Recording with Custom Stream
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/views/camera-view.md
This C# method demonstrates how to record a video to a specific `FileStream` and then stop the recording. A `FileStream` must be provided to `StartVideoRecording` for this overload to work. Ensure the stream is properly disposed.
```csharp
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);
}
```
--------------------------------
### IsNullOrEmptyStateTrigger C# Code-Behind
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Triggers/index.md
The C# code-behind for the IsNullOrEmptyStateTrigger XAML example.
```csharp
public sealed partial class IsNullOrEmptyStateTriggerSample : Page
{
public IsNullOrEmptyStateTriggerSample()
{
this.InitializeComponent();
MyCollection = new List();
}
public IEnumerable MyCollection { get; set; }
}
```
--------------------------------
### Initialize .NET MAUI Community Toolkit Camera
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/get-started.md
Add the using statement for CommunityToolkit.Maui and call UseMauiCommunityToolkitCamera during application bootstrapping to enable camera functionality.
```csharp
using CommunityToolkit.Maui;
```
```csharp
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp()
.UseMauiCommunityToolkitCamera()
```
--------------------------------
### Basic Expander Usage in C#
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/views/Expander.md
Shows how to instantiate and configure an Expander control programmatically in C#, defining its Header and Content.
```csharp
using CommunityToolkit.Maui.Views;
var expander = new Expander
{
Header = new Label
{
Text = "Baboon",
FontAttributes = FontAttributes.Bold,
FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label))
}
};
expander.Content = new HorizontalStackLayout
{
Padding = new Thickness(10),
Children =
{
new Image
{
Source = "http://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Papio_anubis_%28Serengeti%2C_2009%29.jpg/200px-Papio_anubis_%28Serengeti%2C_2009%29.jpg",
Aspect = Aspect.AspectFill,
HeightRequest = 120,
WidthRequest = 120
},
new Label
{
Text = "Baboons are African and Arabian Old World monkeys belonging to the genus Papio, part of the subfamily Cercopithecinae.",
FontAttributes = FontAttributes.Italic
}
}
};
```
--------------------------------
### IsEqualStateTrigger C# Code-Behind
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Triggers/index.md
The C# code-behind for the IsEqualStateTrigger XAML example.
```csharp
public sealed partial class IsEqualStateTriggerSample : Page
{
public IsEqualStateTriggerSample()
{
this.InitializeComponent();
MyProperty = "SomeValue";
}
public string MyProperty { get; set; }
}
```
--------------------------------
### UserHandPreferenceStateTrigger C# Code-Behind
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Triggers/index.md
Provides the C# code-behind for the UserHandPreferenceStateTrigger XAML example.
```csharp
public sealed partial class UserHandPreferenceStateTriggerSample : Page
{
public UserHandPreferenceStateTriggerSample()
{
this.InitializeComponent();
}
}
```
--------------------------------
### NetworkConnectionStateTrigger C# Code-Behind
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Triggers/index.md
Provides the C# code-behind for the NetworkConnectionStateTrigger XAML example.
```csharp
public sealed partial class NetworkConnectionStateTriggerSample : Page
{
public NetworkConnectionStateTriggerSample()
{
this.InitializeComponent();
}
}
```
--------------------------------
### NetworkHelper Sample XAML
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Helpers/NetworkHelper.md
This XAML code demonstrates how to bind to properties exposed by the NetworkHelper.
```xaml
```
--------------------------------
### IsNotEqualStateTrigger C# Code-Behind
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Triggers/index.md
Provides the C# code-behind for the IsNotEqualStateTrigger XAML example.
```csharp
public sealed partial class IsNotEqualStateTriggerSample : Page
{
public IsNotEqualStateTriggerSample()
{
this.InitializeComponent();
MyProperty = "AnotherValue";
}
public string MyProperty { get; set; }
}
```
--------------------------------
### Initialize .NET MAUI Community Toolkit MediaElement
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/get-started.md
Add the using statement for CommunityToolkit.Maui and call UseMauiCommunityToolkitMediaElement during application bootstrapping. Set enableForegroundService to true if Rich Media Notifications or background playback on Android are required.
```csharp
using CommunityToolkit.Maui;
```
```csharp
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp()
.UseMauiCommunityToolkitMediaElement(enableForegroundService: true);
```
--------------------------------
### ControlSizeTrigger C# Code-Behind
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Triggers/index.md
Provides the C# code-behind for the ControlSizeTrigger XAML example.
```csharp
public sealed partial class ControlSizeTriggerSample : Page
{
public ControlSizeTriggerSample()
{
this.InitializeComponent();
}
}
```
--------------------------------
### Using UserStoppedTypingBehavior with C# Markup
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/behaviors/user-stopped-typing-behavior.md
This example utilizes the CommunityToolkit.Maui.Markup package for a more concise C# implementation. It chains behavior configuration and binding directly to the Entry control definition.
```csharp
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));
}
}
```
--------------------------------
### ConstrainedBox Multiples Code-Behind
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Primitives/ConstrainedBox.md
Provides the data context for the ConstrainedBox multiples example.
```csharp
public sealed partial class ConstrainedBoxMultipleSample : Page
{
public ConstrainedBoxMultipleSample()
{
this.InitializeComponent();
this.DataContext = this;
}
}
```
--------------------------------
### Add Styles using Fluent Methods
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/maui/markup/extensions/style.md
Demonstrates using fluent Add methods to configure a Label's style, including app theme bindings, multiple setters, behaviors, and event triggers.
```csharp
new Label
{
Style = new Style()
.AddAppThemeBinding(Label.TextColorProperty, Colors.Red, Colors.Orange)
.Add((Label.BackgroundColorProperty, Colors.White), (Label.FontAttributesProperty, FontAttributes.Bold))
.Add(new NumericValidationBehavior())
.Add(new EventTrigger { Event = nameof(Label.Focused) });
}
```
--------------------------------
### ConstrainedBox Scaling Code-Behind
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/Primitives/ConstrainedBox.md
Provides the data context for the ConstrainedBox scaling example.
```csharp
public sealed partial class ConstrainedBoxScaleSample : Page
{
public ConstrainedBoxScaleSample()
{
this.InitializeComponent();
this.DataContext = this;
}
}
```
--------------------------------
### RangeSelector XAML Definition
Source: https://github.com/microsoftdocs/communitytoolkit/blob/main/docs/windows/RangeSelector/index.md
Defines the RangeSelector control in XAML. This is a basic setup.
```xaml
```