c# - 如何在后面的代码中将标签文本绑定到字符串属性?
问题描述
我查看了我能找到的所有关于此的帖子,但没有一个以我理解的方式回答这个问题。我正在慢慢尝试构建一个跟踪纸牌游戏生活的应用程序。现在,我只是想让生命总数显示出来,这样我就可以定义我的方法,让两个递增和递减按钮完成它们的工作。我以前在后端工作过,所以我知道如何让按钮来做他们的事情,但我不明白为什么我的生活总字符串没有显示为文本。
这是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)
{
}
}
}
解决方案
您应该绑定到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 可绑定属性
推荐阅读
- sql - 将这些查询组合成一个返回的函数
- routes - 通过 Rails 路由中的 URL 参数匹配
- flutter - 如何使用 Navigator 移动到有状态页面
- javascript - TypeError:无法读取未定义的属性“映射”-尝试将值映射到卡时
- php - 半空间、半空间或零空间的正则表达式 POSIX 表达式
- android - MediaController 不尊重视图的动画
- android - 将标签放在右上角
- spring - 对于 postgresql db,我没有使用 hibernate 获得唯一列
- sql - 如何使用 Kotlin 的 Exposed ORM 获得具有正确行为的 createdAt 和 lastModified 字段?
- spring-boot - Run a springboot jar with Jenkins Build command