当资源在 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"];

您可以使用TryGetValueResourceDictionary:中获取单个

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

最新更新