【问题标题】:Xamarin.Forms Use Local Variable in XAMLXamarin.Forms 在 XAML 中使用局部变量
【发布时间】:2021-07-12 05:36:07
【问题描述】:

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

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>

【问题讨论】:

标签: c# xaml xamarin xamarin.forms mobile


【解决方案1】:

不确定您的其余代码是什么样子,但我的虚拟示例可能会帮助您弄清楚您需要做什么。 既然你在 cmets 中提到你有 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;
        }

}

这会给你这样的输出:

【讨论】:

  • 首先感谢您的帮助。但我想通了。我希望 number 成为类中的普通属性,而不是 ItemSource 的属性。所以在我这样做的方式 number 被认为是项目源的一个属性,但事实并非如此,所以没有显示任何内容。我通过给内容页面一个名称来解决它,然后绑定 Text 属性 {Binding Source={x:Reference Name=ordersPage}, Path=Number}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-11
相关资源
最近更新 更多