![](/img/trans.png)
[英]How to use value of a C# variable in XAML in Xamarin.Forms?
[英]Xamarin.Forms Use Local Variable in XAML
假设我在 my.cs 文件中有一个名为number的变量,我想在我的 xaml 页面中将 label 的文本设置为number的值。 我怎样才能做到这一点? 我检查了这个链接,但它没有帮助我。 我错过了什么吗?
CS:
public partial class OrdersPage : ContentPage
{
public string number = Methods.GetMessage("number");
public OrdersPage()
{
InitializeComponent();
Init();
}
private async void Init()
{
this.BindingContext = this;
....
}
xaml:
<Label FontSize="Subtitle">
<Label.FormattedText>
<FormattedString>
<Span Text="{Binding number}" FontAttributes="Bold"/>
<Span Text=": " FontAttributes="Bold"/>
<Span Text="{Binding PickupNo}" TextColor="{Binding Source={x:Static static:Constants.PRIMARY_COLOR}}"/>
</FormattedString>
</Label.FormattedText>
</Label>
不确定您的代码的 rest 是什么样子,但我的虚拟示例可能会帮助您弄清楚您需要做什么。 既然你在评论中提到你有CollectionView
,我猜它看起来像这样:
XAML:
<CollectionView x:Name="collectionView" ItemsSource="{Binding MyCollection}">
<CollectionView.ItemTemplate>
<DataTemplate>
<Label FontSize="Subtitle">
<Label.FormattedText>
<FormattedString>
<Span Text="{Binding number}" FontAttributes="Bold"/>
<Span Text=": " FontAttributes="Bold"/>
<Span Text="{Binding PickupNo}"/>
</FormattedString>
</Label.FormattedText>
</Label>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
在 your.cs 文件中,您应该有 MyItem 的 MyCollection,定义如下:
public partial class OrdersPage : ContentPage
{
public class MyItem
{
public string number { get { return Methods.GetString("number"); } }
public string PickupNo { get; set; }
}
public ObservableCollection<MyItem> MyCollection { get; set; } = new ObservableCollection<MyItem>();
public OrdersPage ()
{
InitializeComponent();
MyItem Item = new MyItem();
Item.PickupNo = "123456789";
MyCollection.Add(Item);
BindingContext = this;
}
}
这会给你一个 output 像这样:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.