评估OnPlatform <t>

时间:2018-06-19 16:18:39

标签: xamarin.forms

如果我使用代码从资源字典中检索OnPlatform<T>的实例,如何在当前平台上对其进行评估?

public static string FontName =>
   ((OnPlatform<string>) Application.Current.Resources["Font"]) ...

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式实现它:

<Application.Resources>
    <ResourceDictionary>
        <OnPlatform x:Key="MyPadding"
         x:TypeArguments="Thickness"
            iOS="0, 20, 0, 0"
            Android="0, 0, 0, 0"/>
    </ResourceDictionary>
</Application.Resources>

var thickness = (OnPlatform<Thickness>)Application.Current.Resources["MyPadding"];
var realThickness = (Thickness)thickness;

var thickness = (Thickness)(OnPlatform<Thickness>)Application.Current.Resources["MyPadding"];

或者,您可以创建扩展方法:

public static class ApplicationExtensions
{
    public static T GetResourceOnPlatform<T>(this Application app, string key) => (T)(OnPlatform<T>)app.Resources[key];
}

然后以另一种方式使用它:

var thickness = Application.Current.GetResourceOnPlatform<Thickness>("MyPadding");