簡體   English   中英

在C#后端中將資源聲明為Class時,如何訪問資源?

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

我的主要資源如下所示:

<?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"];

您可以使用TryGetValueResourceDictionary獲取一個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM