2015-08-21 21 views
2

我需要綁定TextColorLabel。但Label是與SelectedArticleBindingContext,因此綁定是不與任何工作以外的SelectedArticle的綁定(我錯了嗎?使用BindingContext將StackLayout中Label的TextColor綁定

public Color ArticleFontColor { get; set; }

<StackLayout BindingContext="{Binding SelectedArticle}"> 
    <Label Text="{Binding Title}" FontSize="Large" 
      TextColor="{Binding ArticleFontColor}" 
      FontAttributes="Bold"></Label> 
</StackLayout> 

思考,我嘗試了StackLayout內使用樣式,但該值不會綁定。

<ContentPage.Resources> 
    <ResourceDictionary> 
     <Style x:Key="labelStyle" TargetType="Label"> 
      <Setter Property="TextColor" Value="{Binding ArticleFontColor}" /> 
     </Style> 
    </ResourceDictionary> 
</ContentPage.Resources> 


<Label Text="{Binding Title}" FontSize="Large" 
      Style="{StaticResource labelStyle}" 
      FontAttributes="Bold"></Label> 

TextColor可以改變運行時,這就是爲什麼我需要結合

回答

0

很多搜​​索之後,我發現這個解決方案:

添加x:Name標記您的ContentPage或根佈局。

例如。

<ContentPage ... ... x:Name="MyRoot">

然後,使用x:Name作爲參考,並得到其BindingContext

TextColor="{Binding BindingContext.ArticleFontColor, Source={Reference MyRoot}}"

0

樣式不會從綁定值工作。

第一種選擇: 你不需要的樣式爲:

<Label Text="{Binding Title}" FontSize="Large" 
      TextColor="{Binding ArticleFontColor}" 
      FontAttributes="Bold"></Label> 

如果ArticleFontColor不是Color類型(例如僅string。),你應該使用IValueConverter實現做轉換( https://developer.xamarin.com/guides/cross-platform/xamarin-forms/user-interface/xaml-basics/data_binding_basics/ - 搜索IValueConverter)。

第二個選項: 使用觸發器設置樣式: http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/triggers/(數據觸發部分)

+0

'ArticleFontColor'是'Color' 另外,我的第一個代碼片段是您的第一選擇。但它沒有工作,可能是因爲它的父'StackLayout'有''SelectedArticle'的'BindingContext'。 'ArticleFontColor'不是一個屬性,它顯示'SelectedArticle'。那就是爲什麼這個問題。 –

相關問題