Alan2
Alan2

Reputation: 24592

How do I create a ResourceDictionary in Xamarin?

I am trying to follow this example:

public class App : Application
{
    public App ()
    {
        var buttonStyle = new Style (typeof(Button)) {
            Setters = {
                ...
                new Setter { Property = Button.TextColorProperty,   Value = Color.Teal }
            }
        };

        Resources = new ResourceDictionary ();
        Resources.Add ("buttonStyle", buttonStyle);
        ...
    }
    ...
}

Global Styles

But it doesn't work / recognize the new ResourceDictionary(). Does anyone know what I might be doing wrong?

Upvotes: 2

Views: 1293

Answers (4)

Milen
Milen

Reputation: 8877

You can add to your setter to style's Setters collection too. Code in PCL:

        using Xamarin.Forms; 

        .....
        this.Resources = new ResourceDictionary();
        var style = new Style(typeof(Button));
        style.Setters.Add(new Setter { Property = Button.TextColorProperty,   Value = Color.Teal });

        Resources.Add("MyButtonStyle", style);

Upvotes: 2

Richard Hubley
Richard Hubley

Reputation: 2320

Application should already have a resource dictionary, especially if defined in the XAML.

Check if Resources is null

Check if Application.Current.Resources is null

if both are null you can create a new ResourceDictionary(), you may need to include using Xamarin.Forms;

Upvotes: 1

Ziyad Godil
Ziyad Godil

Reputation: 2680

You create class in resource file

namespace MyNameSpace.Resources
{
    public static class Styles
    {
        public static Style ButtonStyle = new Style(typeof(Button))
        {
            Setters = {
                new Setter { Property = Button.TextColorProperty,   Value = Color.Teal }

            }
        };
    }
}

In your xaml.cs file you can use directly like

MyBtn.Style = Styles.ButtonStyle; 

Upvotes: 1

JKennedy
JKennedy

Reputation: 18817

You need to implement resource dictionary.

Create a class like so:

public class MyResourceDictionary : ResourceDictionary
{

}

Then in your code you should be able to do:

Resources = new MyResourceDictionary();
Resources.Add("ButtonStyle",buttonStyle);

Upvotes: 0

Related Questions