首页 > 解决方案 > 如何在后面的代码中将标签文本绑定到字符串属性?

问题描述

我查看了我能找到的所有关于此的帖子,但没有一个以我理解的方式回答这个问题。我正在慢慢尝试构建一个跟踪纸牌游戏生活的应用程序。现在,我只是想让生命总数显示出来,这样我就可以定义我的方法,让两个递增和递减按钮完成它们的工作。我以前在后端工作过,所以我知道如何让按钮来做他们的事情,但我不明白为什么我的生活总字符串没有显示为文本。

这是xml代码:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="Notes.MainPage">
<StackLayout Margin="10,35,10,10">
    <Label 

           Text="{Binding lifeTotalString}"
           FontSize="30"
           HorizontalOptions="Center"
           FontAttributes="Bold"/>

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Button Text="-"
                Clicked="btnDecrement" />
        <Button Grid.Column="1"
                Text="+"
                Clicked="btnIncrement"/>
    </Grid>
</StackLayout>

这是后面的代码

namespace Notes
{
public partial class MainPage : ContentPage
{
    int lifeTotal = 20;

    public MainPage()
    {
        InitializeComponent();
        string lifeTotalString = lifeTotal.ToString();
    }

    void btnDecrement(object sender, EventArgs e)
    {

    }

    void btnIncrement(object sender, EventArgs e)
    {

    }
}

}

标签: c#androidxamarindata-binding

解决方案


您应该绑定到BindableProperty后面的代码并BindingContext正确设置:

public partial class MainPage : ContentPage
{
    int lifeTotal = 20;

    public static readonly BindableProperty lifeTotalStringProperty = BindableProperty.Create(
            nameof(lifeTotalString),
            typeof(string),
            typeof(MainPage),
            default(string));

    public string lifeTotalString
    {
        get => (string)GetValue(lifeTotalStringProperty);
        set => SetValue(lifeTotalStringProperty, value);
    }

    public MainPage()
    {
        InitializeComponent();
        lifeTotalString = lifeTotal.ToString();

        BindingContext = this;
    }

    void btnDecrement(object sender, EventArgs e)
    {
        lifeTotal--;

        lifeTotalString = lifeTotal.ToString();
    }

    void btnIncrement(object sender, EventArgs e)
    {
        lifeTotal++;

        lifeTotalString = lifeTotal.ToString();
    }
}

数据绑定连接两个对象的属性,称为源和目标。在代码中,需要两个步骤:必须将目标对象的 BindingContext 属性设置为源对象,并且必须在目标对象上调用 SetBinding 方法(通常与 Binding 类一起使用)以绑定该对象的属性对象到源对象的属性。

目标属性必须是可绑定属性,这意味着目标对象必须派生自 BindableObject。

您可以阅读文档了解更多详细信息:数据绑定Xamarin.Forms 可绑定属性


推荐阅读