如何以编程方式/代码隐藏的方式在Xamarin中设置样式



我需要在代码后面设置样式。我该如何做到这一点?我已经在应用程序中设置了样式,但我在Idom上使用,似乎我无法将OnPlatform添加到相同的样式中,所以我决定继续使用Idom,并将其设置在页面的后面

我有这个,这抛出了一个异常

if (DefaultSettings.DevicePlatform == "iOS" )
{
layout.Style = (Style)Resources["Relative"];
}
else
{
layout.Style = (Style)Resources["RelativeAndroid"];
}

App.xaml

<Style x:Key="YouriOSStyle" TargetType="RelativeLayout">
<Setter Property="BackgroundColor" Value="Blue"/>
</Style>
<Style x:Key="YourAndroidStyle" TargetType="RelativeLayout">
<Setter Property="BackgroundColor" Value="Red"/>
</Style>

背后的代码

// better statement would be this
if(Device.RuntimePlatform == Device.iOS)
{
layout.SetDynamicResource(RelativeLayout.StyleProperty, "YouriOSStyle");
}
else
{
layout.SetDynamicResource(RelativeLayout.StyleProperty, "YourAndroidStyle");
}

最新更新