Home > Back-end >  How do I set the style for an item in a c# content page?
How do I set the style for an item in a c# content page?

Time:07-21

I added the following style in Styles.xaml.

<Style x:Key="ButtonOutline" TargetType="Button">
        <Setter Property="BackgroundColor" Value="{AppThemeBinding Dark={StaticResource ButtonColorDark}, Light={StaticResource ButtonColor}}" />
        <Setter Property="TextColor" Value="{AppThemeBinding Dark={StaticResource TextColorDark}, Light={StaticResource TextColor}}" />
        <Setter Property="BorderColor" Value="{StaticResource Primary}" />
        <Setter Property="BorderWidth" Value="2" />
        <Setter Property="Margin" Value="10" />
        <Setter Property="HeightRequest" Value="50" />
</Style>

I want to set the style in c#. If I do

grid.Add(new Button
        {
            Text = "Clear",
            Style = Style.LoadFromXaml("ButtonOutline")
            
        }, 1, 1);

Then the program crashes with a System.Xml.XmlException: 'Data at the root level is invalid. Line 1, position 1.' exception.

CodePudding user response:

Loadfromxaml was not working, not sure why. I'm able to get the style using this:

Application.Current.Resources.TryGetValue("ButtonOutline", out object buttonStyle);
grid.Add(new Button
    {
    Text = "Clear",
    Command = vm.ClearCommand,
    Style = (Style)buttonStyle
}, 1, 1);
  • Related