xamarin - 在 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"];
解决方案
您可以使用TryGetValue
来从您的ResourceDictionary
:
if (Application.Current.Resources.TryGetValue("DetailLabel", out object style))
{
someLabel.Style = (Style)style;
}
推荐阅读
- reactjs - 如何使用分页处理 React Router 中的多个参数?
- c++ - 如何创建一个柯南包,包括对可以在所有平台上打包的仅标头库的测试
- javascript - 赛普拉斯检查正文中不存在字符串,不包括块或 div
- c# - 当我移动一个控件时,客户端矩形是重复的 WinForms
- nginx - Nginx 向浏览器返回 502,但在 curl 上运行良好
- r - R插入符号:{中的错误:任务1失败-“没有可用的重要性值”
- flutter - Web chrome中的Flutter http不安全请求
- javascript - 将 React Navigation 添加到项目后的 EISDIR
- steam - 为通过 openid 认证的第三方用户激活 Steam 游戏
- java - 避免杰克逊改变时间