How to reference a StyleClass from the code-behind page?

This compiles just fine but blows up in the iOS simulator when the view loads:

                    public MyTestPage()
                    {
                        InitializeComponent();

                        int i = 1; int iLen = 16;
                        for (i = 1; i <= iLen; i++) {
                            Label label =new Label();
                            label.StyleClass.Add("BarL");  // Works if this line is commented out.
                            label.Text = "C";
                            C.Children.Add(label);
                        }
                    }

The StyleClass "BarL" is defined in an inline in the XAML page. So, why doesn't the code-behind know about it?

Tagged:

Best Answer

Answers

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    StyleClass??? No idea what you're trying to use. Is that an iOS thing you're trying to use at the platform-agnostic shared layer?
    Do you mean Style?
    Or are you trying to apply HTML to XAML? XAML is not HTML and trying to use HTML/CSS in XAML is a total cluster and should be avoided at all costs. If you're trying to use styles just do it the way XAML has always done it for 15 years.
    http://redpillxamarin.com/2018/07/19/2018-104-resources-styles-and-themes/

  • ScottPendletonScottPendleton Member ✭✭

    Thanks for that link.

  • ScottPendletonScottPendleton Member ✭✭

    I like the XAML style in App.xaml, as recommended by @ClintStLaurent, over using an html-type cascading style sheet, especially since the new CSS approach does not work with all the styles. So xaml or C# will be needed anyway.

  • JohnHardmanJohnHardman GBUniversity mod

    @ScottPendleton said:
    I like the XAML style in App.xaml, as recommended by @ClintStLaurent, over using an html-type cascading style sheet, especially since the new CSS approach does not work with all the styles. So xaml or C# will be needed anyway.

    AFAIK, StyleClass is unrelated to the CSS stuff. It could be useful in the early days of developing an app, but I'd probably replace it before release in an effort to get the best possible performance (I say that before having measured the performance implications of using it, but I have my suspicions...)

  • jmacias91jmacias91 Member ✭✭

    This work for me:

    Label label =new Label();
    List<string> listStyle = new List<string> { "BarL" };
    label.StyleClass = listStyle;
    
Sign In or Register to comment.