我想做什么
最近我一直在探索XAML资源字典。它们非常强大,但为了进一步减少需要进行的任何修改,我想使用一些基本的算术运算来更改Entry
的HeightRequest
属性。
我已经很好地利用了OnPlatform
和OnIdiom
来处理不同方面,比如FontSize
。
对于iOS平台,我想使输入框的HeightRequest
为20+(FontSize)
。使用OnIdiom
已经设置了FontSize
(对于平板电脑略微增加)。
在完美的世界里,我尝试做的核心问题可能看起来像这样:
<Setter Property="HeightRequest" Value="{DynamicResource StandardFontSize}+10">
"有效"的解决方法
如果我使用OnIdiom
和OnPlatform
的组合,则有一个有效的解决方案。
<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XamarinDesigner.App"
xmlns:local="clr-namespace:XamarinDesigner"
>
<Application.Resources>
<ResourceDictionary>
<OnIdiom x:Key="StandardFontSize" x:TypeArguments="x:Double" Tablet="22" Phone="18"/>
<Style x:Key="MyEntry" TargetType="Entry">
<Setter Property="FontSize" Value="{DynamicResource StandardFontSize}"/>
<Setter Property="HeightRequest">
<Setter.Value>
<OnIdiom x:TypeArguments="x:Double">
<OnIdiom.Phone>
<OnPlatform x:TypeArguments="x:Double" iOS="30"/>
</OnIdiom.Phone>
<OnIdiom.Tablet>
<OnPlatform x:TypeArguments="x:Double" iOS="40"/>
</OnIdiom.Tablet>
</OnIdiom>
</Setter.Value>
</Setter>
<Setter Property="VerticalOptions" Value="Center"/>
</Style>
</ResourceDictionary>
</Application.Resources>
</Application>
使用这种“解决方案” - 我需要显式设置值并自己进行计算。虽然这个方法可行,但我希望能够执行基本算术运算来找到
FontSize
的值,并将一些数字添加到它上面。
我尝试过的
在另一次尝试中,我找到了一个转换器并尝试将其适应我的用例。虽然没有智能提示或构建/编译错误,但应用程序在打开后立即崩溃。可以在上面链接的ArithmeticConverter.cs文件中找到。
<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XamarinDesigner.App"
xmlns:local="clr-namespace:XamarinDesigner"
>
<Application.Resources>
<local:ArithmeticConverter x:Key="AScript"/>
<ResourceDictionary>
<OnIdiom x:Key="StandardFontSize" x:TypeArguments="x:Double" Tablet="22" Phone="18"/>
<Style x:Key="MyEntry" TargetType="Entry">
<Setter Property="FontSize" Value="{DynamicResource StandardFontSize}"/>
<Setter Property="HeightRequest" Value="{Binding Converter={StaticResource AScript},ConverterParameter=Int32.Parse(20+{DynamicResource StandardFontSize}}"/>
<Setter Property="VerticalOptions" Value="Center"/>
</Style>
</ResourceDictionary>
</Application.Resources>
</Application>
我不完全理解转换器的使用,以及在App.xaml中值内部使用的{Binding}
也是新的东西。通过转换器提供的示例,我认为我已经接近正确了,可能只需要一个正确的方向。
是否有可能仅在App.xaml
中(或使用转换器)进行这种基本的算术功能?我希望尽可能地将所有内容都包含在此文件中。
在我的搜索中发现的其他解决方案提到了视图模型的使用,但这是我想要应用于每个平台/方言的“全局”更改,因此我无法看到该适应如何工作。
感谢您的时间!
StandardFontSize
,然后在转换器内部进行所需的数学计算。这样,你就可以消除对ConverterParameter
和正则表达式的需要。 - jsanalytics