Accessing Style Resources from C# - Xamarin.Forms
Since you defined your style inside App.xaml:
createSL.Style = (Style)Application.Current.Resources["blueButton"];
Please try to do this way
Create style in your App constructor and add this in resource like this:
public App ()
{
var buttonStyle = new Style (typeof(Button)) {
Setters = {
...
new Setter { Property = Button.TextColorProperty, Value = Color.Teal }
}
};
Resources = new ResourceDictionary ();
Resources.Add ("blueButton", buttonStyle);
...
}
After that use this style and set to button like this:
Button createSL = new Button();
createSL.Text = "Create Stack Layout";
createSL.Style = (Style)Application.Current.Resources ["blueButton"];
Styles can be defined at local and application level:
var buttonWithStyleFromLocalResources = button1; //button1 defined in XAML
var buttonWithStyleFromApplicationResources = button2; //button2 defined in XAML
ResourceDictionary localResourceDictionary = Resources;
//try to access local style with key "KeyForStyle"
if (localResourceDictionary.TryGetValue("KeyForStyle", out object value) && value is Style)
{
buttonWithStyleFromLocalResources.Style = (Style)value;
}
//try to access application style with key "KeyForStyle" (from App.xaml)
ResourceDictionary applicationResourceDictionary = Application.Current.Resources;
if (applicationResourceDictionary.TryGetValue("KeyForStyle", out value) && value is Style)
{
buttonWithStyleFromApplicationResources.Style = (Style)value;
}