【问题标题】:How to bind Label text to string property in code behind?如何在后面的代码中将标签文本绑定到字符串属性?
【发布时间】:2020-06-30 03:49:24
【问题描述】:

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

这里是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# android xamarin data-binding


【解决方案1】:

您应该在后面的代码中绑定到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 结合使用 class) 必须在目标对象上调用以绑定该对象的属性 对象到源对象的属性。

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

您可以阅读文档了解更多详情:data-bindingsXamarin.Forms Bindable Properties

【讨论】:

    猜你喜欢
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多