我可以为每个尺寸参数创建绑定,并在应用程序启动时使用某种缩放因子重新计算最佳尺寸,但这将需要大量新代码并且在字体大小方面实现起来很麻烦。
最终我做的是创建一个完整的命名空间来保存所有需要的类。所以如果有人感兴趣,可以在
GitHub上查看我的完整代码。
基本上,这都归结于像这样迭代 Avalonia 逻辑树:
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
的构造函数如下:
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);
}
}
我可以通过迭代所有创建的绑定来应用新的UI缩放因子,方法如下:
public void ApplyScaling(double scalingFactor)
{
PreScalingAction?.Invoke();
foreach (IScalable binding in Bindings.Values)
{
binding.ApplyScaling(scalingFactor);
}
PostScalingAction?.Invoke();
}
再次说明,这里放不下太多的代码,但希望能让你了解我的解决方案是如何实现的。
这是结果:
![enter image description here](https://istack.dev59.com/vazQf.webp)
可以按比例缩放到这个大小
![enter image description here](https://istack.dev59.com/EKHCL.webp)