簡體   English   中英

Xamarin.Forms 在 XAML 中使用局部變量

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM