Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set style in Xamarin programmatically / code - behind

I need to set style at the back of the code. How do I achieve that? I have set style in the app, however I am using on Idom and seems I can't add OnPlatform to the same style so I have decided to keep on Idiom and set this in the back of the page

I have this and this throws an exception

if (DefaultSettings.DevicePlatform == "iOS" )
{
    layout.Style = (Style)Resources["Relative"];
}
else
{
    layout.Style = (Style)Resources["RelativeAndroid"];
}
like image 577
iko popo Avatar asked Dec 06 '25 18:12

iko popo


1 Answers

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>

Code behind

// better statement would be this
if(Device.RuntimePlatform == Device.iOS)
{
   layout.SetDynamicResource(RelativeLayout.StyleProperty, "YouriOSStyle");
}
else
{
   layout.SetDynamicResource(RelativeLayout.StyleProperty, "YourAndroidStyle");
}
like image 167
Shubham Tyagi Avatar answered Dec 08 '25 14:12

Shubham Tyagi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!