Получение информации о элементах ItemSource

У меня приложение WPF с использованием SQL. Я вношу информацию из базы данных в ItemControl и все отлично работает, но только занялся удалением одного элемента из списка и баз данных. Так вошел в ступор.

Окно с самой привязкой данных

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();



        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;
            List<int> IdLineBasketProduct = new List<int>();
            try
            {

                string querystring = $"select Код_Корзины from Корзина where Код_Корзины > '{UserInfo.lastLineBasket}'";

                SqlCommand command = new SqlCommand(querystring, dataBase.GetConnection());
                dataBase.openConnection();

                reader = command.ExecuteReader();

                while (reader.Read())
                {
                    IdLineBasketProduct.Add(Convert.ToInt32(reader["Код_Корзины"]));

                }
            }
            catch (Exception ex)
            {
                // MessageBox.Show(ex);
            }
            finally
            {
                if (reader != null && !reader.IsClosed)
                    reader.Close();
                dataBase.closeConnection();
            }


            SqlDataReader reader2 = null;
            foreach (int line in IdLineBasketProduct)
            {
                try
                {

                    string querystring = $"select Название, Цена, Картинка from Товар inner join Корзина on Товар.Код_Товара = Корзина.Код_Товара Where Код_Корзины = '{line}'";

                    SqlCommand command = new SqlCommand(querystring, dataBase.GetConnection());
                    dataBase.openConnection();

                    reader2 = command.ExecuteReader();

                    while (reader2.Read())
                    {
                        byte[] imageBytes = (byte[])reader2["Картинка"];
                        basketItems.Items.Add(new
                        {
                            ImageItem = ImgFromBytes(imageBytes),
                            TextItem = Convert.ToString(reader2["Название"]),
                            PriceItem = Convert.ToString(reader2["Цена"]) + "₽"
                        });
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    if (reader2 != null && !reader2.IsClosed)
                        reader2.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 DeleteProduct_Button_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}

XAML этого окна:

<Window x:Class="Practice.Basket"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Practice"
        mc:Ignorable="d"
        Title="SkateBoard" Height="600" Width="400" WindowStartupLocation="CenterScreen">
    
    
    
    <Window.Resources>
        <ResourceDictionary>
            <DataTemplate x:Key="myTaskTemplate">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="200"/>
                        <ColumnDefinition Width="100"/>
                        <ColumnDefinition Width="100"/>
                    </Grid.ColumnDefinitions>

                    <Image Source="{Binding ImageItem}" Grid.Column="0"/>
                    <TextBlock Text="{Binding TextItem}" TextWrapping="Wrap"  Grid.Column="1"/>
                    
                    <StackPanel Orientation="Vertical" Grid.Column="2">
                        <TextBlock Text="{Binding PriceItem}"/>
                        <Button FontSize="10" HorizontalAlignment="Left" Width="60" Content="Убрать" Click="DeleteProduct_Button_Click" />
                    </StackPanel>

                </Grid>

            </DataTemplate>
            <Style TargetType="Button">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Button">
                            <Border CornerRadius="10"
                                Background="{TemplateBinding Background}">

                                <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                              VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ResourceDictionary>
        
    </Window.Resources>

    <Grid x:Name="basketGrid">
        <Grid.RowDefinitions>
            <RowDefinition Height="100"/>
            <RowDefinition Height="385"/>
            <RowDefinition Height="100"/>
            <RowDefinition Height="Auto" MinHeight="0"/>
        </Grid.RowDefinitions>


        <StackPanel Grid.Row="0" Orientation="Vertical">

            <Button Cursor="Hand" Grid.Row="0" Click="Back_Button_Click" VerticalAlignment="Top" HorizontalAlignment="Left" Height="50" Width="50">
                <Border x:Name="Border" 
                                Width="{TemplateBinding ContentControl.Width}"
                                CornerRadius="20">
                    <Image Source="Resources/User/back-icon.png"/>
                </Border>
            </Button>

            <TextBlock Text="Корзина" FontSize="36" HorizontalAlignment="Center" FontWeight="Bold"/>
        </StackPanel>
        <ScrollViewer   Grid.Row="1">
            <ItemsControl x:Name="basketItems"  Grid.Row="1" 
              ItemTemplate="{StaticResource myTaskTemplate}"/>
        </ScrollViewer>


        <StackPanel Grid.Row="2" Orientation="Horizontal">
            <TextBlock Text="Сумма заказа: " VerticalAlignment="Center" FontSize="20" FontWeight="Bold"/>
            <Label  VerticalAlignment="Center" FontSize="16" Height="25" Width="100"/>
            <Button Content="Заказать" VerticalAlignment="Center" FontSize="26" Margin="30,0,0,0" Width="110" Height="60"/>
        </StackPanel>
    </Grid>
</Window>


Ответы (0 шт):