Моя проблема заключается в том, как отразить в метке значение, введенное клиентом в поле ввода. Чтобы все стало ясно, давайте начнем с нашей базы данных. Наша база данных Немного информации о нашей базе данных в реальном времени. В нашей ТАБЛИЦЕ ДОСТАВКИ у нас есть 3 вида доставки (стандартная, резервная и экспресс). Экспресс, по сути, это срочная доставка, и мы потребуем ПЛАТУ ДОСТАВКИ с заказчика.
Другая таблица PRODUCT. На данный момент у нас есть 2 продукта: МИНЕРАЛЬНЫЕ (PROD1) И ИГРИСТЫЕ (PROD2). Цена PROD1 35, а PROD2 40.
Что я пробовал прямо сейчас, так это то, что я поместил SelectedIndexChanged в тип доставки моего сборщика и тип продукта сборщика. //Это мое событие типа доставки
private async void Picker_DeliveryType_SelectedIndexChanged(object sender, EventArgs e)
{
DELIVERY deliverySave = Picker_DeliveryType.SelectedItem as DELIVERY;
var selectedDeliveryItem = deliverySave.deliveryType;
var note = deliverySave.deliveryFee;
if (selectedDeliveryItem == "Express")
{
await DisplayAlert("Note", "Estimated Delivery: 2 hours from now", "OK");
labelDeliveryFee.Text = "Delivery Fee:" + note;
entryfieldReservationDate.IsEnabled = false;
}
else if (selectedDeliveryItem == "Standard")
{
await DisplayAlert("Note", "Within the day", "OK");
entryfieldReservationDate.IsEnabled = true;
}
else
{
await DisplayAlert("Note", "Enter Reservation Date", "OK");
entryfieldReservationDate.IsEnabled = true;
}
}
//Это событие типа моего продукта
private void Picker_ProductType_SelectedIndexChanged(object sender, EventArgs e)
{
PRODUCT prod = Picker_ProductType.SelectedItem as PRODUCT;
var selectedProductItem = prod.productType;
var productPricing = prod.productPrice;
if (selectedProductItem == "Mineral")
{
labelProductPrice.Text = Convert.ToString(productPricing);
}
else
{
labelProductPrice.Text = Convert.ToString(productPricing);
}
}
И мой ожидаемый результат: я хочу, чтобы 2 SelectedIndexChanged поместили внутри моей кнопки заказа. // это моя кнопка заказа нажмите кнопку сейчас
async private void Button_Clicked(object sender, EventArgs e)
{
if (selectedDeliveryType == "Standard")
{
if (selectedProductItem == "Mineral")
{
//some code here
waterOrder.orderTotalAmount = totalprice;
}
else
{
//some code here
waterOrder.orderTotalAmount = totalprice;
}
}
else if (selectedDeliveryType == "Reservation")
{
if (selectedProductItem == "Mineral")
{
//some code here
waterOrder.orderTotalAmount = totalprice;
}
else
{
//some code here
waterOrder.orderTotalAmount = totalprice;
}
}
else
{
int deliveryfee = deliverySave.deliveryFee;
if (selectedProductItem == "Mineral")
{
//some code here
waterOrder.orderTotalAmount = totalprice;
}
else
{
//some code here
waterOrder.orderTotalAmount = totalprice;
}
}
//some code here
var SaveData = await waterorderRepos.Save(waterOrder);
var SaveDataToCustomerNotification = await waterorderRepos.SaveCustomerNotification(customerNotification);
if (SaveData)
{
await this.DisplayAlert("Order", "Order successfully", "OK");
ClearData();
CloseAllPopup();
return;
}
else
{
await this.DisplayAlert("Order", "We cannot process your order at the moment.", "OK");
}
}
Я покажу вам некоторое визуальное представление между моей работой сейчас и моим ожидаемым результатом. Это образ.
Пожалуйста, помогите мне, ребята, не знаю, как это сделать. Кроме того, без MVVM, пожалуйста, вызовите IDK, как это сделать. Большое спасибо.
У вас есть ссылка на ваш комментарий, сэр? Я просто новичок в xamarin.
Область видимости переменных — базовая концепция C#
Исходя из сложности вашего кода, я рекомендую использовать для реализации шаблон MVVM. Я создал демо и выполнил вашу функцию.
Вы можете обратиться к следующему коду:
1. создайте модель представления MyViewModel.cs
public class MyViewModel: INotifyPropertyChanged
{
public ObservableCollection<Delivery> Deliveries { get; set; }
private Delivery _deliverySelectedItem;
public Delivery DeliverySelectedItem
{
get => _deliverySelectedItem;
set {
SetProperty(ref _deliverySelectedItem, value);
// update the TotalAmount
caculateTotalAmount();
}
}
public ObservableCollection<Product> Products { get; set; }
//add SelectedItem here
private Product _productSelectedItem;
public Product ProductSelectedItem
{
get => _productSelectedItem;
set {
SetProperty(ref _productSelectedItem, value);
// update the TotalAmount
caculateTotalAmount();
}
}
private int _quantity;
public int Quantity
{
get => _quantity;
set
{
SetProperty(ref _quantity, value);
// update the TotalAmount
caculateTotalAmount();
}
}
private int _totalAmount;
public int TotalAmount
{
get => _totalAmount;
set
{
SetProperty(ref _totalAmount, value);
}
}
private void caculateTotalAmount() {
if (String.IsNullOrEmpty(Quantity.ToString() ) || Quantity == 0) {
TotalAmount = 0;
return;
}
if (ProductSelectedItem!=null && DeliverySelectedItem!=null) {
TotalAmount = ProductSelectedItem.productPrice * Quantity + DeliverySelectedItem.deliveryFee;
}
}
public MyViewModel() {
Products = new ObservableCollection<Product>();
Products.Add(new Product { ProductId = 01, productType = "Products", productPrice = 10 });
Products.Add(new Product { ProductId = 02, productType = "02", productPrice = 12 });
Products.Add(new Product { ProductId = 03, productType = "Products", productPrice = 13 });
Products.Add(new Product { ProductId = 04, productType = "Products", productPrice = 15 });
Deliveries = new ObservableCollection<Delivery>();
Deliveries.Add(new Delivery { deliveryFee = 10, deliveryType = "Express" });
Deliveries.Add(new Delivery { deliveryFee = 20, deliveryType = "Standard" });
Deliveries.Add(new Delivery { deliveryFee = 30, deliveryType = "Standard" });
}
bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (Object.Equals(storage, value))
return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
2.создать класс Delivery.cs и Product.cs
public class Delivery
{
public string deliveryType { get; set; }
public int deliveryFee { get; set;}
}
public class Product
{
public int ProductId { get; set; }
public string productType { get; set; }
public int productPrice { get; set; }
}
3.MainPage.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"
xmlns:pickerapp2023112 = "clr-namespace:PickerApp2023112"
x:Class = "PickerApp2023112.MainPage">
<ContentPage.BindingContext>
<pickerapp2023112:MyViewModel></pickerapp2023112:MyViewModel>
</ContentPage.BindingContext>
<StackLayout>
<Picker x:Name = "Picker_DeliveryType" ItemsSource = "{Binding Deliveries}" ItemDisplayBinding = "{Binding deliveryFee}" SelectedItem = "{Binding DeliverySelectedItem}"
Title = "Select a delivery type"
TitleColor = "Red">
</Picker>
<Picker x:Name = "Picker_ProductType" ItemsSource = "{Binding Products}" ItemDisplayBinding = "{Binding productPrice}" SelectedItem = "{Binding ProductSelectedItem}"
Title = "Select a product type"
TitleColor = "Red">
</Picker>
<StackLayout Orientation = "Horizontal">
<Label Text = "Please input quantity: " BackgroundColor = "CadetBlue"/>
<Entry Placeholder = "0" Text = "{Binding Quantity}" TextColor = "Red" HorizontalOptions = "FillAndExpand"></Entry>
</StackLayout>
<Label x:Name = "labelDeliveryFee" Text = "{Binding DeliverySelectedItem.deliveryFee,StringFormat='The delivery free is {0:F1}'}" HorizontalOptions = "StartAndExpand" BackgroundColor = "Yellow"></Label>
<Label x:Name = "labelProductPrice" Text = "{Binding ProductSelectedItem.productPrice,StringFormat='The product price is {0:F2}'}" HorizontalOptions = "StartAndExpand" BackgroundColor = "Yellow"></Label>
<StackLayout Orientation = "Horizontal">
<Label Text = "The total amount: " BackgroundColor = "CadetBlue"/>
<Entry Placeholder = "0" Text = "{Binding TotalAmount}" TextColor = "Red" HorizontalOptions = "FillAndExpand"></Entry>
</StackLayout>
</StackLayout>
</ContentPage>
Примечание:
1. Я добавляю два объекта для свойства SelectedItem двух средств выбора и реализую интерфейс INotifyPropertyChanged для этой ViewModel, если мы изменим значение свойства, пользовательский интерфейс будет обновляться автоматически. То же самое верно и для других свойств.
private Delivery _deliverySelectedItem;
public Delivery DeliverySelectedItem
{
get => _deliverySelectedItem;
set {
SetProperty(ref _deliverySelectedItem, value);
}
}
public ObservableCollection<Product> Products { get; set; }
//add SelectedItem here
private Product _productSelectedItem;
public Product ProductSelectedItem
{
get => _productSelectedItem;
set {
SetProperty(ref _productSelectedItem, value);
}
}
В этом состоянии нам не нужно добавлять событие SelectedIndexChanged для Picker.
Спасибо, сэр, я постараюсь понять ваше решение и посмотрю, куда вставить код при получении из firebase.
Здравствуйте, сэр, в вашем общедоступном MyViewModel (), могу ли я заменить это в этом коде? codeshare.io/1YzZ7q смотрите ссылку спасибо.
Да, вы можете инициализировать значение в конструкторе вашей модели представления.
Хорошо, сэр, я попробую этот сэр.
Если вы хотите ссылаться на переменные из нескольких мест в своем коде, объявите их как переменные уровня класса, а не объявляйте их локально внутри ваших методов.