首页 > 解决方案 > 在 C# 后端声明为类时如何访问资源?

问题描述

我的主要资源如下所示:

<?xml version="1.0" encoding="utf-8"?>
<Application xmlns:converters="clr-namespace:Japanese" 
             xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             x:Class="Japanese.App">
    <Application.Resources>
        <ResourceDictionary>
        <ResourceDictionary Source="/Resources/DetailRes.xaml" />

我有这个资源文件:

<?xml version="1.0" encoding="UTF-8" ?>
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                    x:Class="Japanese.DetailRes">
    <Style x:Key="DetailLabel" TargetType="Label">
        <Setter Property="FontSize">
            <Setter.Value>
                <OnPlatform x:TypeArguments="x:Double">
                    <On Platform="iOS" Value="35" />
                    <On Platform="Android" Value="35" />
                </OnPlatform>
            </Setter.Value>
        </Setter>
        <Setter Property="VerticalOptions" Value="Center" />
        <Setter Property="LineBreakMode" Value="WordWrap" />
        <Setter Property="HorizontalTextAlignment" Value="Center" />
    </Style>
</ResourceDictionary>

在 XAML 中,我像这样访问它:

<t:BaseFrameButtonTemplate xmlns="http://xamarin.com/schemas/2014/forms" 
                  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
                  xmlns:t="clr-namespace:Japanese.Templates" 
                  xmlns:local="clr-namespace:Japanese;assembly=Japanese" 
                  x:Class="Japanese.Templates.RoundButtonText" x:Name="this" >

    <Label Text="{Binding Text, Source={x:Reference this}}" 
           Style="{StaticResource DetailRes}" 
           x:Name="Label" />
</t:BaseFrameButtonTemplate>

我想在 C# 中访问它,但不知道该怎么做。我试过这个,但它没有找到资源:

Label.Style = (Style)Application.Current.Resources["DetailRes"];

标签: xamarinxamarin.forms

解决方案


您可以使用TryGetValue来从您的ResourceDictionary:

if (Application.Current.Resources.TryGetValue("DetailLabel", out object style))
{
    someLabel.Style = (Style)style;
}

推荐阅读