2016-07-05 34 views
2

我試圖製造類似組屬性附加傷害到所有標籤網格如何通過Xamarin XAML {} GroupStyle添加樣式定義的ResourceDictionary

我知道如何使這裏面,只是這樣做:

<Grid RowSpacing="2" Padding="2,0,2,0"> 
    <Grid.Resources> 
     <ResourceDictionary> 
      <Style BasedOn="{StaticResource Font-Awesome}" TargetType="Label"/> 
     </ResourceDictionary> 
    </Grid.Resources> 
     <Label Text="31 &#xf083;" Grid.Column="0" TextColor="#2764B5" XAlign="Start"/> 

     <Label Text="91 &#xf083;" Grid.Column="1" TextColor="#A0A1A2" XAlign="Center"/> 

     <Label Text="12 &#xf083;" Grid.Column="2" TextColor="#A0A1A2" XAlign="End"/> 
</Grid> 

但它的醜陋和冗餘

我想要做的smetthing像

<Grid RowSpacing="2" Padding="2,0,2,0" Style="{StaticResource grd-actions}"> 
    <Label Text="31 &#xf083;" Grid.Column="0" TextColor="#2764B5" XAlign="Start"/> 

    <Label Text="91 &#xf083;" Grid.Column="1" TextColor="#A0A1A2" XAlign="Center"/> 

    <Label Text="Compartilhar &#xf083;" Grid.Column="2" TextColor="#A0A1A2" XAlign="End"/> 
</Grid> 

而在App靜態資源包括資源字典網格,是這樣的:

<Style x:Key="gd-actions" TargetType="Grid"> 
    <Setter Property="Resources"> 
     <Setter.Value> 
     <ResourceDictionary> 
      <Style BasedOn="{StaticResource Font-Awesome}" TargetType="Label"/> 
     </ResourceDictionary> 
     </Setter.Value> 
    </Setter> 
</Style> 

我已經是有很多方法試圖但它的跳投拋出某種異常!

有人可以幫我嗎?

+0

您想使用XAML樣式像CSS - 但這不是一個完美的模擬。你的第一個例子(你不喜歡)確實是這樣的正確方法。 –

+0

我明白了,所以我無法將樣式定位到網格並像CSS一樣更改所有項目?將所有樣式分組爲僅隱含在視圖元素內部將是非常好的。我真的不喜歡調用靜態資源給所有的東西 –

+1

樣式不會傳播到子元素。 'BindingContext'傳播,並且資源字典的內容的可用性沿元素樹向下傳播,但不是樣式。最終,這是因爲'Style'中的'Setter'元素需要知道目標元素類型是什麼,因爲這是它將查找依賴項屬性定義的地方。 CSS完全不同。 –

回答

1

我想最乾淨的方法是使用Explicit StylesGlobal Resources。聲明爲Labels的風格Application Resources,然後在你的標籤只是添加Style Property

應用:

<Application xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="xforms_test.App"> 
    <Application.Resources> 
     <ResourceDictionary> 
      <Style x:Key="labelAquaStyle" TargetType="Label"> 
       <Setter Property="HorizontalOptions" Value="Center" /> 
       <Setter Property="TextColor" Value="Aqua" /> 
      </Style> 
     </ResourceDictionary> 
    </Application.Resources> 
</Application> 

而在你的頁面:

<Grid RowSpacing="2" Padding="2,0,2,0"> 
    <Label Grid.Column="0" Text="These labels" Style="{StaticResource labelAquaStyle}" /> 
    <Label Grid.Column="1" Text="are demonstrating" Style="{StaticResource labelAquaStyle}" /> 
    <Label Grid.Column="2" Text="explicit styles" Style="{StaticResource labelAquaStyle}" /> 
</Grid> 
+0

但是在每個元素上調用樣式都很無聊/多餘,沒有辦法像CSS樣式一樣? –

+1

如果樣式是Global(你想在你的應用程序的每個Label中使用該樣式),你可以去除每個元素的Style屬性,否則沒有其他方法。 – jzeferino

相關問題