xamarin.forms - xamarin 表单中标签的数据绑定部分
问题描述
我在 Xamarin 表单中使用标签。我必须显示一个基本上是一个句子的文本,但该字符串的一部分包含一个我从 api 调用中获得的数字,并且字符串的其余部分是固定的。
我想使用数据绑定来设置那部分。例子 :
文本可以是:“你肯定能赢 {0} 美元”
{0} 值来自 api 并希望使用数据绑定来绑定它。
需要用于绑定此类字符串的语法。
解决方案
您可以使用模型绑定到标签中的数据。就像这样:在 xaml 中:
<Label Text="{Binding Name,StringFormat='You can win {0} dollars for sure'}"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
在 ContentPage 中,应该绑定上下文:
nativeDataTemple = new NativeDataTemple();
BindingContext = nativeDataTemple;
并且 Molde(您自定义的NativeDataTemple)应该包含绑定属性,如下所示:
private string name = "520";
public string Name
{
set
{
if (name != value)
{
name = value;
OnPropertyChanged("Name");
}
}
get
{
return name;
}
}
并在您的模型中,当名称值在后台更改时,将INotifyPropertyChanged添加到模型中,并添加方法
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
那么你想在哪里更改数据,只需这样做:
nativeDataTemple.Name = "550";
有问题可以参考这个官方文档
推荐阅读
- android - 以渐变为背景时屏幕过渡模糊
- android - 如何在没有状态栏的情况下设置 Flutter AppBar 透明
- python - 如何使用 rasterio 编写 tiff 文件?
- google-apps-script - Google Apps 脚本中的 PayPal REST API 错误 400
- python - Manifest.in 似乎被忽略了
- sql - Postgres 子查询运行速度极慢,为什么?
- rest - 包含附加字段的 RESTful API
- gradle - 一些 Gradle 命令行选项不起作用
- ios - MP Charts iPhone,实时绘图时的性能问题
- sql - 如何在sql查询中从起始年份获取每年的金额