2017-03-16 32 views
4

我想在app.xaml上設置我的資源,然後在應用程序的不同視圖中使用它,但是當我設置顏色時,應用程序會崩潰u.u,有人可以幫助我嗎?如何從全球資源中獲取用戶顏色?

的App.xaml

<Application.Resources> 
    <ResourceDictionary> 
     <Color x:Key="Primary">#FFC107</Color> 
    </ResourceDictionary> 
</Application.Resources> 

使用它在StackLayout

<StackLayout Orientation="Vertical" BackgroundColor="{StaticResource Primary}"> 
+0

'樣式'會希望'StyleTemplate'作爲它的資源。你只是想要而已; '' –

+0

是的,但它不工作在那種模式 –

+0

模式?它可能想要一個類型爲'Brush'的資源而不是'Color'類型? –

回答

3

你是否在App.xaml.cs中調用了InitializeComponent?

+0

非常感謝那是缺失的部分。它現在正在工作! (Y) –

1
BackgroundColor="{DynamicResource Primary}" 

它是一個DynamicResource,而不是一個靜態資源。

這裏是我的代碼看起來像例如:

的App.xaml有

<Color x:Key="titleColor">Green</Color> 

和page.xaml具有

TextColor="{DynamicResource titleColor}" 
+0

使用DynamicResource不會使我的應用程序崩潰,但它不會將顏色應用於我的stackLayout的背景。 –

+1

@AlexanderRojas,奇怪的是,我在整個應用程序中都使用了它,我也將全局樣式應用於某些佈局和控件。在這一點上,我只能想到檢查「farid JAD7」在後面的代碼中調用InitializeComponent的建議。 '\t \t public App(){ \t \t \t InitializeComponent(); //加載全局樣式' – Allister

2

你需要使用靜態資源,我覺得一個很好的資源給你:

https://blog.xamarin.com/easy-app-theming-with-xamarin-forms-styles/

所以,你需要做到以下幾點:

1中的App.xaml

<Application 
    xmlns="http://xamarin.com/schemas/2014/forms" 
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
    x:Class="MonkeyTweet.App"> 
    <Application.Resources> 
     <ResourceDictionary> 
      <Color x:Key="backgroundColor">#33302E</Color> 
      <Color x:Key="textColor">White</Color> 
     </ResourceDictionary> 
    </Application.Resources> 
</Application> 

2-使用StaticResource標記擴展引用預定義的資源,在應用級定義ResourceDictionary

<Label Text="{Binding Text}" TextColor = "{StaticResource textColor}"/> 
+0

這就是我做的,沒有工作! –

+0

所以,我認爲問題不是來自這個問題 –

+0

如果我使用StaticResource我的應用程序崩潰! –