简体   繁体   中英

How can I access a resource when it's declared as a Class in C# back end?

My main resources look like this:

<?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" />

I have this resource file:

<?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>

In XAML I access it like this:

<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>

I would like to access this in C# but do not know how to do it. I tried this but it does not find the resource:

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

You can use the TryGetValue to obtain a single from your ResourceDictionary :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM