0

Это приложение WPF (магазин продуктов), связанное с базой данных SQL. Я пытаюсь сделать корзину: Есть класс BasketConstructor в котором есть коллекция, я хочу при нажатии на кнопку окне добавлять в нее id товаров. А в самой корзине доставать id и запросами получать информацию о товаре. Но в саму корзину содержимое не передается. Как сделать чтобы передавалось...

Вот код BasketConstructor:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Windows;

namespace Practice { internal class BasketConstructor : INotifyPropertyChanged { DataBase dataBase = new DataBase(); public ObservableCollection<int> idContainer { get { return IdContainer; } set { IdContainer = value; OnPropertyChanged("idContainer"); } }

    private ObservableCollection&lt;int&gt; IdContainer = new ObservableCollection&lt;int&gt;();
    public float SummPrice { get { return SummBasketCalculation(); } set { SummPrice = value; OnPropertyChanged(&quot;SummPrice&quot;); } }

    //Сделать кнопку покупки (запись в бд всех товаров и удаление)

    public void AddProduct(int id)
    {
        idContainer.Add(id);

    }

    private int SummBasketCalculation()
    {
        int summ = 0;
        SqlDataReader reader = null;

        try
        {
            foreach (int i in idContainer)
            {
                string querystring = $&quot;select Цена from Товар where Код_Товара = '{i}'&quot;;
                SqlCommand command = new SqlCommand(querystring, dataBase.GetConnection());
                dataBase.openConnection();

                reader = command.ExecuteReader();

                while (reader.Read())
                {
                    summ += Convert.ToInt32(reader[&quot;Цена&quot;]);
                }
            }
            return summ;
        }
        catch (Exception ex)
        {
             MessageBox.Show(ex.ToString());
            return 0;
        }
        finally
        {
            if (reader != null &amp;&amp; !reader.IsClosed)
                reader.Close();

            dataBase.closeConnection();
        }
    }




    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler propertyChangedEvent = PropertyChanged;
        if (propertyChangedEvent != null)
        {
            propertyChangedEvent(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

}

Это код окна в Корзины, в котором я вызываю коллекцию с id:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.IO;
using System.Collections.ObjectModel;

namespace Practice { /// <summary> /// Логика взаимодействия для Basket.xaml /// </summary> public partial class Basket : Window { DataBase dataBase = new DataBase();

    BasketConstructor bconstructor = new BasketConstructor();
    ObservableCollection&lt;int&gt; id { get { return bconstructor.idContainer; } }
    public Basket()
    {
        InitializeComponent();
        basketGrid.Background = new SolidColorBrush(Color.FromRgb(223, 229, 229));
        Loaded += Basket_Loaded;
    }

    private void Basket_Loaded(object sender, RoutedEventArgs e)
    {
        SqlDataReader reader = null;

        try
        {
            foreach (int i in bconstructor.idContainer)   // именно в этой строчке длина равна 0
            {
                string querystring = $&quot;select Название, Цена, Картинка from Товар where Код_Товара = '{i}'&quot;;
                SqlCommand command = new SqlCommand(querystring, dataBase.GetConnection());
                dataBase.openConnection();

                reader = command.ExecuteReader();

                while (reader.Read())
                {
                    byte[] imageBytes = (byte[])reader[&quot;Картинка&quot;];
                    basketItems.Items.Add(new
                    {
                        ImageItem = ImgFromBytes(imageBytes),
                        TextItem = Convert.ToString(reader[&quot;Название&quot;]),
                        PriceItem = Convert.ToString(reader[&quot;Цена&quot;]) + &quot;₽&quot;
                    });
                }
            }
        }
        catch (Exception ex)
        {
            // MessageBox.Show(ex);
        }
        finally
        {
            if (reader != null &amp;&amp; !reader.IsClosed)
                reader.Close();
            dataBase.closeConnection();
        }


        //basketItems.ItemsSource = new[] { new и тд}
    }

    private static BitmapImage ImgFromBytes(byte[] arr)
    {
        var image = new BitmapImage();

        using (var mem = new MemoryStream(arr))
        {
            mem.Position = 0;
            image.BeginInit();
            image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.UriSource = null;
            image.StreamSource = mem;
            image.EndInit();
        }
        image.Freeze();

        return image;
    }

    private void Back_Button_Click(object sender, RoutedEventArgs e)
    {
        UserPage userPage = new UserPage();
        userPage.Show();
        Close();
    }
}

}

Вот так я добавляю элемент в коллекцию в другом окне

private void One_Bread_Click(object sender, RoutedEventArgs e)
        {
            BasketConstructor bconstruct = new BasketConstructor();
            bconstruct.AddProduct(1);
        }
  • 1
    Наверно не делать постоянно новый класс BasketConstructor? Неужели вас тут new BasketConstructor(); не смутило ключевое слово new? Передавайте ссылку через конструктор на уже существующий класс, а не делайте новый. – EvgeniyZ Nov 20 '22 at 11:39
  • ООП - что такое объект? Что делает new? – aepot Nov 20 '22 at 11:45
  • а не можете показать кодом, как сделать передачу ссылки через конструктор – blinkopec Nov 20 '22 at 11:57
  • 1
    https://ru.stackoverflow.com/a/835223/220553 – EvgeniyZ Nov 20 '22 at 12:02
  • я только не могу разобраться, как мне объявить класс BasketConstructor в классе корзины, но при этом не объявлять новый объект BasketConstructor. (Создал новый класс, через который использую методы из BasketConstructor) – blinkopec Nov 20 '22 at 15:31

0 Answers0