当资源在 C# 后端被声明为类时,如何访问它? [英] How can I access a resource when it's declared as a Class in C# back end?

查看:26
本文介绍了当资源在 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 中,我像这样访问它:

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>

我想在 C# 中访问它,但不知道如何去做.我试过了,但没有找到资源:

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

推荐答案

您可以使用 TryGetValue 从您的 ResourceDictionary 中获取单个:

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

这篇关于当资源在 C# 后端被声明为类时,如何访问它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆