如何从Xamarin Forms中的C#中的App.xaml访问颜色?

Uro*_*ros 10 xamarin xamarin.forms

在App.xaml我有这个代码:

<Application.Resources>
    <ResourceDictionary>
        <Color x:Key="Yellow">#ffd966</Color>
    </ResourceDictionary>
</Application.Resources>
Run Code Online (Sandbox Code Playgroud)

在C#中我有这个代码:

public Color BackgroundColor
{
    get { return IsSelected ? Color.Yellow : Color.White; }
}
Run Code Online (Sandbox Code Playgroud)

我想用App.xaml中的颜色改变Color.Yellow.如何从C#中的App.xaml引用颜色?

Dil*_*mah 22

isSelected ? (Color) Application.Current.Resources["Yellow"] : Color.White;
Run Code Online (Sandbox Code Playgroud)

我认为不需要Conversion Color.FromHex(),因为您将资源定义为颜色.希望有所帮助.


fma*_*oni 14

以防万一,如果Color被引用MergedDictionaries

<ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
        <resources:Colors />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)

你需要像这样:

Application.Current.Resources.TryGetValue("Yellow", out var yellowColor)
Run Code Online (Sandbox Code Playgroud)

如果你使用Application.Current.Resources["Yellow"]它会抛出一个 key not found 异常。

HIH

  • 这应该是最佳答案,因为坦白说每个人都使用 MergedDictionaries,不是吗? (3认同)

Ger*_*uis 9

您应该能够像这样访问它Application.Current.Resources["Yellow"]

如果是颜色的话,它会更像;

public Color BackgroundColor
{
    get { return IsSelected ? Application.Current.Resources["Yellow"].ToString() : Color.White }
}
Run Code Online (Sandbox Code Playgroud)