CommunityToolkit.Maui.Options 允许开发人员自定义 CommunityToolkit.Maui。 工具包的行为可能有所不同,具体取决于这些设置。
调用 .UseMauiCommunityToolkit() 时,应在启动时分配 Options:
var builder = MauiApp.CreateBuilder();
builder.UseMauiCommunityToolkit(options =>
{
options.SetShouldSuppressExceptionsInConverters(false);
options.SetShouldSuppressExceptionsInBehaviors(false);
options.SetShouldSuppressExceptionsInAnimations(false);
})
SetShouldSuppressExceptionsInConverters
设置为 true 时,如果实现 CommunityToolkit.Maui.Converters.BaseConverter 的转换器引发 Exception,则会捕获 Exception,通过 Debug.WriteLine() 记录,并返回预先确定的默认值。
默认值是 false。
示例
调用 .UseMauiCommunityToolkit() 时启用此选项:
var builder = MauiApp.CreateBuilder();
builder.UseMauiCommunityToolkit(options =>
{
options.SetShouldSuppressExceptionsInConverters(true);
})
默认返回值
设置为 true 时,如果 Converter 引发 Exception,将返回默认值。
包括两个默认值:
public object? ICommunityToolkitValueConverter.DefaultConvertReturnValue { get; set; }Default value returned when Convert(object? value, Type targetType, object? parameter, CultureInfo? culture)引发Exception
public object ICommunityToolkitValueConverter.DefaultConvertBackReturnValue { get; set; }Default value returned when ConvertBack(object? value, Type targetType, object? parameter, CultureInfo? culture)引发Exception
下面是设置 BoolToObjectConverter 默认值的示例:
XAML
<ContentPage.Resources>
<SolidColorBrush x:Key="TrueColorBrush">Green</SolidColorBrush>
<SolidColorBrush x:Key="FalseColorBrush">Red</SolidColorBrush>
<toolkit:BoolToObjectConverter x:Key="BoolToColorBrushConverter"
TrueObject="{StaticResource TrueColorBrush}"
FalseObject="{StaticResource FalseColorBrush}"
DefaultConvertReturnValue="{StaticResource FalseColorBrush}"
DefaultConvertBackReturnValue="False"/>
</ContentPage.Resources>
C#
var boolToColorBrushConverter = new BoolToObjectConverter
{
TrueObject = new SolidColorBrush(Colors.Green),
FalseObject = new SolidColorBrush(Colors.Red),
DefaultConvertReturnValue = new SolidColorBrush(Colors.Red),
DefaultConvertBackReturnValue = false
};
SetShouldSuppressExceptionsInAnimations
设置为 true 时,如果实现 CommunityToolkit.Maui.Behaviors.AnimationBehavior 的 Animation 引发 Exception,则会捕获 Exception 并通过 Debug.WriteLine() 记录。
默认值是 false。
示例
调用 .UseMauiCommunityToolkit() 时启用此选项:
var builder = MauiApp.CreateBuilder();
builder.UseMauiCommunityToolkit(options =>
{
options.SetShouldSuppressExceptionsInAnimations(true);
})
SetShouldSuppressExceptionsInBehaviors
设置为 true 时,如果实现 CommunityToolkit.Maui.Behaviors.BaseBehavior 的 Behavior 引发 Exception,则会捕获 Exception 并通过 Debug.WriteLine() 记录。
默认值是 false。
示例
调用 .UseMauiCommunityToolkit() 时启用此选项:
var builder = MauiApp.CreateBuilder();
builder.UseMauiCommunityToolkit(options =>
{
options.SetShouldSuppressExceptionsInBehaviors(true);
})