【问题标题】:Unified place for resources used in XAML and cs files?XAML 和 cs 文件中使用的资源的统一位置?
【发布时间】:2019-03-13 08:17:31
【问题描述】:

碰巧我为应用程序颜色定义了一个ResourceDictionary 以在 XAML 文件中使用它,并为这些颜色提供了一个静态类以在 cs 代码中使用: 例如:

<ResourceDictionary 
    xmlns="http://xamarin.com/schemas/2014/forms" 
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
    x:Class="MyApp.Themes.AppTheme">
    <Color x:Key="BrandColor">#ffd92e</Color>
    <Color x:Key="BgColor">#343433</Color>
</ResourceDictionary>

和对面的类:

public static class AppColors
{
    public static readonly Color BrandColor = (Color)Application.Current.Resources["BrandColor"];
    public static readonly Color BGColor = (Color)Application.Current.Resources["BgColor"];
}

另一种情况,我在 xaml 和 cs 中都使用图标字体, 在 XAML 中它看起来像 &amp;#xe8d5;,在 cs 中它是:\ue8d5。我想将它们保存在一个文件中,我可以在其中通过 XAML 和 cs 中有意义的名称来引用它们,例如: IconBell = \ue8d5

是否可以在一个地方定义类似的资源并在 XAML 和代码中使用它们?

【问题讨论】:

  • 是的,有可能。但是请确保静态类 AppColors 可以调用所需的 Resources[...]Xaml 直接使用{StaticResource TabColor}.CS 使用Resources ["searchBarStyle"] 或您定义的静态类(Label.TextColor = AppColors.BrandColor)。如果需要转换值,您可以使用IValueConverter 来做到这一点。

标签: xamarin xamarin.forms resourcedictionary


【解决方案1】:

关于颜色问题,很容易解决。您基本上必须创建一个包含您的颜色的类,并在您的 XAML 中使用 x:Static extension 引用它。

您可以这样做来解决您的图标问题,但您可能需要创建一个转换器以在 XAML 中使用它。例如,图标值的重要部分是 "e8d5" 部分,但在 C# 中使用“\u”,而在 XAML 中使用“”。您必须使用图标创建一个类,使用 x:Static 扩展在 XAML 中引用它,并使用转换器从 C# 转换为 XAML,例如:

public class IconConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        try
        {
            string icon = System.Convert.ToString(value);
            return icon.Replace("\u", "&#x");
        }
        catch (Exception)
        {
            throw new InvalidCastException("The value is not a valid string.");
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

这样,您可以在一个独特的 C# 类中统一您的样式,并在您的 XAML 中引用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-19
    • 2018-01-08
    • 1970-01-01
    • 2014-01-28
    • 2012-11-10
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    相关资源
    最近更新 更多