Dima
Dima

Reputation: 1761

Xamarin.Forms CSS selector for custom control

I have a custom control (MyControl) in my Xamarin.Forms project. I wonder if it is possible to style my control with CSS? Currently I do not know how to specify a selector for my custom control.

If I style the control in XAML, I need to import a namespace and use it:

xmlns:ctrls="clr-namespace:DemoApp.Controls"
...
<Style TargetType="ctrls:MyControl"...

CSS also supports namespaces:

@namespace ctlrs "clr-namespace:DemoApp.Controls";

However, if I try to write a CSS rule...

ctrls|MyControl {
    margin: 10;
}

...I get a System.NotSupportedException: 'AT-rules not supported'.

So I wonder if there is a solution for custom control to be styled with CSS.

Upvotes: 0

Views: 561

Answers (2)

Lucas Zhang
Lucas Zhang

Reputation: 18861

Elements with a specific class attribute can be selected with the case sensitive .class selector:

For example , set the style of Label

style.css

.detailPageTitle {
    font-style: bold;
    font-size: medium;
    text-align: center;
}

.detailPageSubtitle {
    text-align: center;
    font-style: italic;
}

in xaml

<ContentPage ...>
    <ContentPage.Resources>
        <StyleSheet Source="/Assets/styles.css" />
    </ContentPage.Resources>
    <ScrollView>
        <StackLayout>
            <Label ... StyleClass="detailPageTitle" />
            <Label ... StyleClass="detailPageSubtitle"/>
            
        </StackLayout>
    </ScrollView>
</ContentPage>

In your case , you should make sure that your custom control has the property Margin.

For more details about using CSS in xamarin.forms you can check here .

Update

You can set the style as following

^MyControl {
                background-color: lightgray;
}

Or you can directly set it in xaml

<ContentPage.Resources>
   <StyleSheet>
            <![CDATA[
            ^MyControl {
                background-color: lightgray;
            }
            ]]>
    </StyleSheet>
 </ContentPage.Resources>
<StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">

  <conv:MyControl Text="1111111"/>
  <conv:MyControl Text="1111111"/>
  <conv:MyControl Text="1111111"/>
  <conv:MyControl Text="1111111"/>
          
</StackLayout>

Upvotes: 0

Ben
Ben

Reputation: 2995

Select element by base class

CSS in file /Styles/styles.css in Xamarin.Forms project:

   ^MyClass {
       font-style: italic;
   }

XAML:

<ContentPage ...
             xmlns:myNamespace="clr-namespace:MyNamespace;assembly=MyAssembly"
             ...
  >
  <ContentPage.Resources>
    ...
    <StyleSheet Source="/Styles/styles.css" />
    ...
  </ContentPage.Resources>
    ...
    <myNamespace:MyClass Text="Text" />
    ...
</ContentPage>

Note:

The ^base selector is specific to Xamarin.Forms, and isn't part of the CSS specification.

Upvotes: 0

Related Questions