我可能会为每个大小参数创建绑定,并使用某种缩放因子在应用程序启动时重新计算最佳大小,但这需要一堆新代码,并且使用字体大小来实现会很痛苦。
这最终就是我所做的。我必须创建一个完全独立的命名空间来保存执行此操作所需的所有类。所以这个答案的代码太多了,但如果有人感兴趣,我会把我的完整代码放在 GitHub 上。
基本上,这一切都归结为像这样迭代 Avalonia LogicalTree:
/// <summary>
/// Recursively registers all <see cref="ILogical"/>s in <paramref name="logicals"/> to the <paramref name="bindingContext"/>.
/// </summary>
/// <param name="logicals">A <see cref="Queue{T}"/> containing the root controls that will be recursively registered.</param>
/// <param name="bindingContext">The <see cref="BindingContext"/> the <see cref="ScalableObject"/>s will be registered to.</param>
public static void RegisterControls(Queue<IEnumerable<ILogical>> logicals, BindingContext bindingContext)
{
while (logicals.Count > 0)
{
IEnumerable<ILogical> children = logicals.Dequeue();
foreach (ILogical child in children)
{
logicals.Enqueue(child.GetLogicalChildren());
if (child is AvaloniaObject avaloniaObject)
{
ScalableObject scalableObject = new ScalableObject(avaloniaObject);
bindingContext.Add(scalableObject);
}
}
}
}
我的构造函数ScalableObject
如下所示:
/// <summary>
/// Initializes a new <see cref="ScalableObject"/> from the provided <paramref name="avaloniaObject"/>.
/// </summary>
/// <param name="avaloniaObject">The <see cref="AvaloniaObject"/> to be mapped to this new instance of <see cref="ScalableObject"/>.</param>
public ScalableObject(AvaloniaObject avaloniaObject)
{
if (avaloniaObject is TextBlock textBlock)
{
Register(avaloniaObject, TextBlock.FontSizeProperty, textBlock.FontSize);
}
if (avaloniaObject is TemplatedControl templatedControl)
{
Register(avaloniaObject, TemplatedControl.FontSizeProperty, templatedControl.FontSize);
}
if (avaloniaObject is Border border)
{
Register(avaloniaObject, Border.CornerRadiusProperty, border.CornerRadius);
}
// .... This goes on like this for a while
}
然后我可以应用一个新的 UI 缩放因子迭代所有创建的绑定,如下所示:
/// <summary>
/// Applies the specified <paramref name="scalingFactor"/> to this <see cref="ScalableObject"/> and all of it's children.
/// </summary>
/// <param name="scalingFactor">The scaling factor to be applied to all <see cref="IScalable"/>s of this <see cref="ScalableObject"/>.</param>
public void ApplyScaling(double scalingFactor)
{
PreScalingAction?.Invoke();
foreach (IScalable binding in Bindings.Values)
{
binding.ApplyScaling(scalingFactor);
}
PostScalingAction?.Invoke();
}
同样,在此答案中放入的代码确实太多,但希望它能让您了解我的解决方案是如何实现的。
这是结果:
![在此处输入图像描述](https://i.stack.imgur.com/vazQf.png)
可以缩放到这个
![在此处输入图像描述](https://i.stack.imgur.com/EKHCL.png)