CommunityToolkit.Maui.Options 允许开发人员自定义 CommunityToolkit.Maui。 工具包的行为可能有所不同,具体取决于这些设置。
Options 应在启动时调用 .UseMauiCommunityToolkit() 时进行赋值:
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。
Example
调用 .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。
Example
调用 .UseMauiCommunityToolkit()时启用此选项:
var builder = MauiApp.CreateBuilder();
builder.UseMauiCommunityToolkit(options =>
{
options.SetShouldSuppressExceptionsInAnimations(true);
})
SetShouldSuppressExceptionsInBehaviors
当设置为 true 时,如果实现了 CommunityToolkit.Maui.Behaviors.BaseBehavior 的 Behavior 抛出 Exception,则会捕获 Exception,并通过 Debug.WriteLine() 将其记录下来。
默认值为 false。
Example
调用 .UseMauiCommunityToolkit()时启用此选项:
var builder = MauiApp.CreateBuilder();
builder.UseMauiCommunityToolkit(options =>
{
options.SetShouldSuppressExceptionsInBehaviors(true);
})