2017-08-30 98 views
0

我需要綁定字符串的背景顏色。 我的XAML代碼:在Xamarin Forms中綁定BackgroundColor屬性ContentPage

<?xml version="1.0" encoding="utf-8" ?> 
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
      x:Class="Fimap.LoadingPage" 
      BackgroundColor="{Binding ColorBackground}"> 
    <ContentPage.Content> 
     <Grid Padding="130" x:Name="griglia"> 
      <Grid.ColumnDefinitions> 
       <ColumnDefinition Width="*"></ColumnDefinition> 
      </Grid.ColumnDefinitions> 
      <Grid.RowDefinitions> 
       <RowDefinition Height="10*"></RowDefinition> 
       <RowDefinition Height="40*"></RowDefinition> 
       <RowDefinition Height="25*"></RowDefinition> 
       <RowDefinition Height="25*"></RowDefinition> 
      </Grid.RowDefinitions> 
      <Image Source="logo.png" Grid.Row="1"></Image> 
      <ActivityIndicator x:Name="loading" Grid.Row="2" IsVisible="true" Color="{Binding ColorBackground}" IsRunning="true" /> 
     </Grid> 
    </ContentPage.Content> 
</ContentPage> 

我隱藏代碼:

... 
public String ColorBackground { get; set; } = "#E40000"; 
... 

我做的公共類()costructor之前設置此ColorBackground

但是不行......我在哪裏錯了?

感謝所有

+0

我不認爲你可以綁定到'顏色'的字符串嘗試綁定到'顏色'屬性 – user1

回答

3

您也需要綁定到Xamarin.Forms.Color,像這樣:public Color ColorBackground { get; set; } = Color.FromHex("#E40000");

,你都需要一個IValueConverter將字符串轉換爲一種顏色。

爲了使數據綁定工作,請確保您設置頁面的BindingContext財產,是這樣的:BindingContext = this;

使用this如果你使用的是同樣在頁面代碼隱藏屬性。如果你想使用任何其他類作爲你的視圖模型,你也可以將它設置爲一個BindingContext。

您可能希望查看MvvmCross的FreshMvvm等MVVM框架,以使您的生活變得更輕鬆。

+0

mhh不工作...看起來綁定的問題..其中是錯誤?我沒有發現... –

+0

您是否爲您的頁面設置了BindingContext? –

+0

ahhh發現問題。我沒有設置BindingContext ...一個愚蠢的錯誤。謝謝。 –