Mr. Developer
Mr. Developer

Reputation: 3417

Binding BackgroundColor properties ContentPage in Xamarin Forms

I've need to binding background color from string. My xaml code:

<?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>

my codebehind code:

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

I did set this ColorBackground before the public Class() costructor.

But don't work...where do I wrong ?

Thanks to all

Upvotes: 3

Views: 6860

Answers (1)

Gerald Versluis
Gerald Versluis

Reputation: 33993

You either need to bind to a Xamarin.Forms.Color, like this: public Color ColorBackground { get; set; } = Color.FromHex("#E40000");

Of you need a IValueConverter to convert the string to a color.

To make data binding work, make sure that you set the BindingContext property of your page, like this: BindingContext = this;

Use this if you use properties which are also in the page code-behind. If you want to use any other class as your view model you can set that as a BindingContext as well.

You might want to look into a MVVM framework like FreshMvvm of MvvmCross to make your life a bit easier.

Upvotes: 14

Related Questions