在 Xamarin Forms 中绑定 ContentPage 的 BackgroundColor 属性

3

我需要将背景颜色绑定到字符串。

我的XAML代码:

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

我的codebehind代码:

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

我在public Class()构造函数之前设置了ColorBackground,但它没有生效...我错在哪里了?

谢谢大家


我认为你无法将string绑定到Color,请尝试将其绑定到一个Color属性。 - JKennedy
1个回答

14

您可以将 Xamarin.Forms.Color 绑定到属性,如下所示:public Color ColorBackground { get; set; } = Color.FromHex("#E40000");

如果需要将字符串转换为颜色,可以使用 IValueConverter

为了使数据绑定工作,请确保设置页面的 BindingContext 属性,如下所示:BindingContext = this;

如果使用页面代码后台中也存在的属性,则使用 this。如果要将任何其他类用作视图模型,则也可以将其设置为 BindingContext。

您可能想了解 MVVM 框架,例如 FreshMvvm 或 MvvmCross,以使您的生活变得更加轻松。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接