如何访问Styles.xaml文件并在c#标记代码中使用它

问题描述 投票:0回答:1

我是 dotnet maui 的新手,我不知道如何在 c# 标记代码中使用 Styles.xaml 表中定义的样式。

当我使用以下代码时,我的应用程序崩溃了

new Label
{
    Text = "Hello, World!",
    Style = (Style)Application.Current.Resources["TitleLabel"]
}

样式存在于样式表中:

<Style TargetType="Label" x:Key="TitleLabel"\>
    <Setter Property="FontFamily" Value="Montserrat" /\>
    <Setter Property="FontSize" Value="20" /\>
    <Setter Property="FontAttributes" Value="None" /\>
    <Setter Property="TextColor" Value="{StaticResource Black}" /\>
</Style\>

那么如何让这种样式与我的 C# 标记代码一起使用?

c# .net maui markup
1个回答
0
投票

更常见的是,

Style
将在 xaml 中被消耗,这相当简单。例如,在使用
TitleLabel
样式的 MainPage 上放置标签可以这样表示。

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="resources_from_code_behind.MainPage">

        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Label
                Style="{StaticResource TitleLabel}"
                Text="Hello, World!"
                FontSize="32"
                HorizontalOptions="Center" />
        </VerticalStackLayout>

</ContentPage>

但是,您的代码似乎在代码隐藏中尝试执行此操作,其中配方可能涉及查询

MergedDictionaries
集合并选择其
Styles.xaml
属性中带有
OriginalString
的第一个集合。我测试了这个并且它有效,但我不能说我推荐它。

public partial class MainPage : ContentPage
{
    int count = 0;

    public MainPage()
    {
        InitializeComponent();
        if (Application
            .Current
            .Resources
            .MergedDictionaries
            .OfType<ResourceDictionary>()
            .FirstOrDefault(_ => _.Source.OriginalString.Contains("Styles.xaml")) is ResourceDictionary styles
            &&
            styles.TryGetValue("TitleLabel", out var obj)
            &&
            obj is Style style)
        {
            var label = new Label
            {
                Style = style,
            };
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.