简体   繁体   中英

Xamarin.Forms Use Local Variable in XAML

Let's say I have a variable in my.cs file called number , I want to set a text of a label in my xaml page to the value of number . How can I do that? I checked this link but it did not help me. am I missing something?

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>

Not sure how the rest of your code looks like, but my dummy example can maybe help you to figure out what you need to do. Since you mentioned in the comments that you have CollectionView , I guess it looks something like this:

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>

In your.cs file you should have MyCollection of MyItem, defined something like this:

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;
        }

}

This will give you an output like this:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM