类型解析的服务称为类型解析管理器(ITypeResolverManager)。它管理着多个 Acss 内置的和用户注册的类型解析器(ITypeResolver)。
Acss 除了内置的类型解析外,你需要自行注册所有用到的类型到 AcssContext 当中。未注册的类型将会无法识别而被略过。我们提供了多种类型解析的注册方式。
特别注意
目前我们没有做命名空间的映射,因此类型重名的几率比较大。如果有这种情况,请自行管理重名类型的别名,避免冲突。
复制 // Add all types, which are derived from AvaloniaObject, in the Avalonia.Controls.dll
// to the type resolver.
var resolver = new GenericTypeResolver<Button>();
复制 // #1 Use Resolver.
public class CustomTypeResolver1 : Resolver
{
// Nothing to do.
}
// #2 Implement IResolver.
public class CustomTypeResolver2 : IResolver
{
protected Dictionary<string, Type> Types;
protected Resolver()
{
Types = new Dictionary<string, Type>();
}
public bool TryAddType(string name, Type type)
{
if (Types.ContainsKey(name))
{
return false;
}
Types.Add(name, type);
return true;
}
public bool TryAddType<T>(string name)
{
if (Types.ContainsKey(name))
{
return false;
}
Types.Add(name, typeof(T));
return true;
}
public bool TryGetType(string name, out Type? type)
{
return Types.TryGetValue(name, out type);
}
public IEnumerable<Type> GetAllTypes()
{
return Types.Values;
}
}
复制 IResolver resolver = new CustomTypeResolver1();
// Map 'Button' to Button.
resolver.TryAddType("Button", typeof(Button));
// Map 'TextBlock' to TextBlock.
resolver.TryAddType<TextBlock>("TextBlock");
// map 'text' to TextBlock.
resolver.TryAddType<TextBlock>("text");
复制 var typeResolverManager = AcssContext.Default.GetService<ITypeResolverManager>();
IResolver resolver = new CustomTypeResolver1();
typeResolverManager.LoadResolver(resolver);
typeResolverManager.LoadResolver(new GenericTypeResolver<App>());
复制 private static AppBuilder BuildAvaloniaApp()
{
return AppBuilder.Configure<App>()
.UsePlatformDetect()
// Use avalonia css stuff.
.UseAcssDefaultContext()
// Type resolver for Nlnet.Avalonia.Svg
.WithTypeResolverForAcssDefaultBuilder(new GenericTypeResolver<Icon>())
// Type resolver for Nlnet.Avalonia.SampleAssistant
.WithTypeResolverForAcssDefaultBuilder(new GenericTypeResolver<Case>());
}