
![](./scrs/11.jpg)

## EditProductWindow.xaml.cs
```
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
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 wpf_connection3.model;

namespace wpf_connection3.Windows
{

    public partial class EditProductWindow : Window, INotifyPropertyChanged
    {
        public int selectedProductIndex { get; set; } = -1;
        public List<ProductType> productTypeList { get; set; }
        public Product currentProduct { get; set; }
        public EditProductWindow(Product editProduct)
        {
            InitializeComponent();
            DataContext = this;
            currentProduct = editProduct;
            root.Title = currentProduct.ID == 0 ? "Новый продукт" : "Редактирование продукта";
            productTypeList = Globals.dataProvider.getProductTypes().ToList();
            if (currentProduct.ID > 0)
            {
                selectedProductIndex = productTypeList.FindIndex(pt => pt.ID == currentProduct.ProductTypeID);

            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        private void Invalidate(string element)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs($"{element}"));
        }
        private void ChangeImageButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog GetImageDialog = new OpenFileDialog();
           
            GetImageDialog.Filter = "Файлы изображений: (*.png, *.jpg)|*.png;*.jpg";

            
            GetImageDialog.InitialDirectory = Environment.CurrentDirectory;
            if (GetImageDialog.ShowDialog() == true)
            {
                
                currentProduct.Image = GetImageDialog.FileName.Substring(Environment.CurrentDirectory.Length);
                                    
                Invalidate(currentProduct.Image);
            }
        }
        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
               
                if (ProductTypeComboBox.SelectedIndex != null)
                {
                    currentProduct.ProductTypeID = ((ProductType)ProductTypeComboBox.SelectedItem).ID;
                }
                else
                {
                    throw new Exception("Не выбран тип продукта");
                }

                                decimal minCost = decimal.Parse(MinCostForAgentTextBox.Text, CultureInfo.InvariantCulture);
                int decIndex = minCost.ToString().IndexOf('.');
                if (minCost > 0 && (decIndex == -1 || minCost.ToString().Length - decIndex <= 2))
                {
                    currentProduct.MinCostForAgent = minCost;
                }
                else
                {
                    throw new Exception("Цена должна быть больше 0 с двумя знаками после точки");
                }

                              string newArticleNumber = ArticleNumberTextBox.Text;
                if (Globals.dataProvider.getArticleCheck(newArticleNumber, currentProduct.ID) == 0)
                {
                    currentProduct.ArticleNumber = newArticleNumber;
                }
                else
                {
                    throw new Exception("Данный артикул уже используется");
                }

                currentProduct.Title = TitleTextBox.Text;
                currentProduct.ProductionPersonCount = Convert.ToInt32(ProductionPersonCountTextBox.Text);
                currentProduct.ProductionWorkshopNumber = Convert.ToInt32(ProductionWorkshopNumberTextBox.Text);
                currentProduct.Description = DescriptionTextBox.Text;

                Globals.dataProvider.saveProduct(currentProduct);
                DialogResult = true;
            }

                  catch (FormatException)
            {
                MessageBox.Show("Используйте только цифры");
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void deleteButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var saleCount = Globals.dataProvider.saleCount(currentProduct.ID);

                if (saleCount > 0)
                    throw new Exception("Нельзя удалять продукт с продажами");

                Globals.dataProvider.removeProductMaterial(currentProduct.ID);
                Globals.dataProvider.removeProductCostHistory(currentProduct.ID);
                Globals.dataProvider.removeProduct(currentProduct.ID);
                DialogResult = true;
                MessageBox.Show("Продукт удален");
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}



```
#### EditProductWindow.xaml
```
<Window x:Class="wpf_connection3.Windows.EditProductWindow"
        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:wpf_connection3.Windows"
        mc:Ignorable="d"
        Title="EditProductWindow" Height="600" Width="800"
         Name="root">
   
    <Grid>
        
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="auto"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="auto"/>
        </Grid.ColumnDefinitions>


        <Image
Name="CurrentProductImage"
Width="200" 
Height="200"
Source="{Binding currentProduct.ImageBitmap}" />
        <StackPanel
      Grid.Column="1"
            Margin="5">

            <Label Content="Артикул"/>
            <TextBox
                Name="ArticleNumberTextBox"
                
                Text="{Binding currentProduct.ArticleNumber}"/>

            <Label Content="Наименование продукта"/>
            <TextBox
                Name="TitleTextBox"
                Text="{Binding currentProduct.Title}"/>

            <Label Content="Тип продукта"/>
            <ComboBox
                Name="ProductTypeComboBox"
                ItemsSource="{Binding productTypeList}"
                SelectedIndex="{Binding selectedProductIndex}"/>

            <Label Content="Количество человек для производства"/>
            <TextBox 
                Name="ProductionPersonCountTextBox"
                Text="{Binding currentProduct.ProductionPersonCount}"/>

            <Label Content="Номер производственного цеха"/>
            <TextBox 
                Name="ProductionWorkshopNumberTextBox"
                Text="{Binding currentProduct.ProductionWorkshopNumber}"/>

            <Label Content="Минимальная стоимость для агента"/>
            <TextBox
                Name="MinCostForAgentTextBox"
                Text="{Binding currentProduct.MinCostForAgent}"/>

            <Label Content="Описание продукта"/>
            <TextBox
                Name="DescriptionTextBox"
                AcceptsReturn="True"
                Height="200"
                Text="{Binding currentProduct.Descrpition}"/>

            <Button
                Name="ChangeImageButton"
                Content="Изменить фото"
                Margin="5"
                Click="ChangeImageButton_Click"/>

            <Button
                Name="SaveButton"
                Content="Сохранить"
                Margin="5"
                Click="SaveButton_Click"/>

            <Button
                Name="deleteButton"
                Content="Удалить продукт"
                Margin="5"
                Click="deleteButton_Click"/>
            
        </StackPanel>
       
    </Grid>
</Window>


```