从 MainPage.xaml.cs 文件中获取 int 变量的值到 Xamarin 中的 MainPage.xaml



我创建了一个项目,其中MainPage.xaml.cs被称为:CarritoDeVentas.xaml.cs如下所示:

using System;
using System.Collections.Generic;
using System.Collections;
using SQLite;
using Xamarin.Forms;
using Saansa.Modelos;
namespace Saansa.Views
{
public partial class CarritoDeVentas : ContentPage
{
public string strQR;
public int price { set; get; }
public CarritoDeVentas()
{
InitializeComponent();
listaArticulosCarrito.ItemsSource = App.listaCarrito;
price = 0;
this.strQR = "";
foreach (Modelos.ArticuloCarrito a in App.listaCarrito) {
price += a.Precio;
}
}
}

我的CarritoDeVentas.xaml是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Saansa.Views.CarritoDeVentas">
<ContentPage.Content>
<StackLayout BackgroundColor="White">
<ListView x:Name="listaArticulosCarrito" BackgroundColor="White">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<StackLayout HorizontalOptions="StartAndExpand">
<Label Text="{Binding Producto}" Padding="7"
TextColor="Black" FontSize="Large"/>
</StackLayout>
<StackLayout Orientation="Horizontal" HorizontalOptions="EndAndExpand">
<Label x:Name="CantidadProducto" Text="{Binding Cantidad}" Padding="7"
TextColor="LightGray" FontSize="Large"/>
<Label x:Name="PrecioProducto"  Text="{Binding Precio}" VerticalOptions="CenterAndExpand"
TextColor="Black" HorizontalOptions="EndAndExpand" FontSize="Large" Padding="7"/>
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<StackLayout Orientation="Horizontal">
<StackLayout>
<Label Text="Precio total de la venta:" HorizontalOptions="StartAndExpand"
Padding="7" Margin="10,0,10,0" FontSize="Medium"/>
</StackLayout>
<StackLayout HorizontalOptions="EndAndExpand">
<Label Text="{Binding price}" Padding="7"/>
</StackLayout>
</StackLayout>
<Button Text="Pagar" BackgroundColor="#673AB7" Clicked="Button_Clicked"
CornerRadius="15" Margin="10"/>
<Button x:Name="QRbut" Text="Generar CodigoQR" BackgroundColor="#26A69A" Clicked="generateQR_Clicked"
CornerRadius="15" Margin="10,0,10,10"/>
</StackLayout>
</ContentPage.Content>

我的问题是:如何在标签上的 xaml 文件中显示 xaml.cs 文件中的 int 价格?我尝试的是尝试绑定,但我不确定我是否这样做了,我是新手。

选项 1 - 直接分配

// XAML
<Label x:Name="MyPrice" Padding="7"/>
// code-behind
MyPrice.Text = price.ToString();

选项 2 - 绑定

// XAML
<Label Text="{Binding price}" Padding="7"/>
// code behind
// you must set the BindingContext for binding to work
this.BindingContext = this;

最新更新