代码之家  ›  专栏  ›  技术社区  ›  Sam

Xamarin Forms在XAML中使用局部变量

  •  0
  • Sam  · 技术社区  · 4 年前

    假设我的.cs文件中有一个变量,名为 ,我想将我的xaml页面中的标签文本设置为值 我该怎么做?我查过了 this link 但这对我没有帮助。我错过了什么吗?

    反恐精英:

    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>
    
    0 回复  |  直到 4 年前
        1
  •  0
  •   adamm    4 年前

    不知道你的其余代码是什么样子的,但我的虚拟示例可能可以帮助你弄清楚你需要做什么。 自从你在评论中提到 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>
    

    在你的.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;
            }
    
    }
    

    这将给你一个这样的输出:

    enter image description here