Can not apply style written in c#

AAA BBB 41 Reputation points
2024-07-17T18:34:26.77+00:00

Hello, i have created style in C# code and tried to apply this style to the frame, named ControlsGroupMainFrame4 (written in XAML). Tried both WinUI and Android apps. Both apps do not throw any error and start fine, but the style is not applied.

Style is in separate class (in separate file):

(By the way, do i need to make this class static?)

public static class MyStyles
{
    static double screenWidthInDips;
    static Style ControlsGroupMainFrameStyle = new Style(typeof(Frame));
    public static Style GetControlsGroupMainFrameStyle()
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            //get screen width in device-independent Units (DIPs)
            DisplayInfo mainDisplayInfo = DeviceDisplay.MainDisplayInfo;
            double screenWidth = mainDisplayInfo.Width; // in pixels
            double density = mainDisplayInfo.Density; // density factor
            screenWidthInDips = screenWidth / density; //screen width in device-independent Units (DIPs)
                                                       //System.Diagnostics.Debug.WriteLine("AAAAAAAAAAAAAAAAAAAAAAA" + screenWidthInDips);///////////////////////////ISTRINTI
            //set style for the frame
            Frame _Frame = new Frame
            {
                BorderColor = Color.FromArgb("#4c4c4c"),
                Margin = new Thickness(0, 0, 0, 5),
                BackgroundColor = (Color)Application.Current.Resources["BackgroundLightGreen"],
                Padding = 0,
                CornerRadius = 5,
                HasShadow = true
            };
            if (screenWidthInDips < 760) { _Frame.HorizontalOptions = LayoutOptions.Fill; } else { _Frame.HorizontalOptions = LayoutOptions.FillAndExpand; };
            if (screenWidthInDips < 760) { _Frame.WidthRequest = -1; } else { _Frame.WidthRequest = 360; };
            if (screenWidthInDips < 760) { _Frame.MinimumWidthRequest = -1; } else { _Frame.MinimumWidthRequest = 360; };
            //assign MyFrame style to the ControlsGroupMainFrame
            ControlsGroupMainFrameStyle = _Frame.Style;
        });
        //return style
        return ControlsGroupMainFrameStyle;
    }
}

Next i try to apply this style to the Frame:

public partial class ConnectionAndUpdate : ContentPage
{
public ConnectionAndUpdate()
{
    InitializeComponent();
    ControlsGroupMainFrame4.Style = MyStyles.GetControlsGroupMainFrameStyle();
}
}

The Frame in the XAML file:

<?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 BackgroundColor="{StaticResource BackgroundDarkGreen}"
                 x:Class="AngryFish.PagesStandard.ConnectionAndUpdate"
                 xmlns:controls="clr-namespace:AngryFish.MyTemplates"
                 Title="Connection and update">
<Frame x:Name="ControlsGroupMainFrame4">
  <StackLayout Style="{StaticResource ControlsGroupMainLayout}">
    <Frame Style="{StaticResource ControlsGroupHeaderFrame}">
      <Label
          Style="{StaticResource ControlsGroupHeaderText}"
          Text="Help"/>
    </Frame>
    <StackLayout Style="{StaticResource ControlsGroupContentLayout}">
      <!--Code in the controls group starts here-->
      <StackLayout
          Orientation="Horizontal">
        <Label
            Style="{StaticResource StandardLabel}"
            Text="Get controller manual online:"/>
        <Image
            x:Name="ImageBook"
            Margin="5,0,0,0"
            Source="other_book_symbol.png"
            Aspect="AspectFit"
            HeightRequest="40"
            HorizontalOptions="Start"/>
      </StackLayout>
      <!--Code in the controls group ends here-->
    </StackLayout>
  </StackLayout>
</Frame>
</ContentPage>
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,207 questions
0 comments No comments
{count} votes

Accepted answer
  1. Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) 29,206 Reputation points Microsoft Vendor
    2024-07-18T07:29:45.08+00:00

    Hello,

    You new a frame in the GetControlsGroupMainFrameStyle method, and set ControlsGroupMainFrameStyle = _Frame.Style;, but the _Frame.Style is null.

    (Note: Because you get the device info in MainThread, and then set the style for Frame, it will cost a few seconds to load the page)

     public static Style GetControlsGroupMainFrameStyle()
          {
              MainThread.BeginInvokeOnMainThread(() =>
              {...
               
                  //assign MyFrame style to the ControlsGroupMainFrame
               //   ControlsGroupMainFrameStyle = _Frame.Style;
                  ControlsGroupMainFrameStyle = new Style(typeof(Frame))
                  {
                     Setters =
                      {
                          new Setter
                          {
                              Property = Frame.BorderColorProperty,
                              Value = Color.FromArgb("#4c4c4c")
                          },
                           new Setter
                          {
                              Property = Frame.MarginProperty,
                              Value =  new Thickness(0, 0, 0, 5),
                          },
                            new Setter
                          {
                              Property = Frame.BackgroundColorProperty,
                              Value = Colors.Green
                          },
                             new Setter
                          {
                              Property = Frame.BorderColorProperty,
                              Value = Color.FromArgb("#4c4c4c")
                          },
                              new Setter
                          {
                              Property =  Frame.PaddingProperty,
                              Value = 0
                          },
                               new Setter
                          {
                              Property = Frame.CornerRadiusProperty,
                              Value = 5
                          },
                                 new Setter
                          {
                              Property = Frame.HasShadowProperty,
                              Value = true
                          },
                                  new Setter
                          {
                              Property = Frame.HorizontalOptionsProperty,
                              Value =  _Frame.HorizontalOptions
                          },
                                  new Setter
                          {
                              Property = Frame.WidthRequestProperty,
                              Value =  _Frame.WidthRequest
                          },
                                  new Setter
                          {
                              Property = Frame.MinimumWidthRequestProperty,
                              Value =  _Frame.MinimumWidthRequest
                          }
     
                      }
                  };
              });
              //return style
              return ControlsGroupMainFrameStyle;
          }
      }
    

    And then you can set the style : ControlsGroupMainFrame4.Style = MyStyles.GetControlsGroupMainFrameStyle();

    Also, it's not clear how you set the Static Style in XAML. You can see Style apps using XAML - .NET MAUI | Microsoft Learn

    Best Regards,

    Wenyan Zhang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful