Загрузка данных
DELETE FROM PickupPoints WHERE Id IS NULL;
БД
CREATE DATABASE ShoesDB
GO
USE ShoesDB
GO
CREATE TABLE Products
(
Id INT PRIMARY KEY IDENTITY(1,1),
Article NVARCHAR(50),
BrandName NVARCHAR(100),
Unit NVARCHAR(20),
Price DECIMAL(10,2),
Supplier NVARCHAR(100),
Manufacturer NVARCHAR(100),
Category NVARCHAR(100),
Discount INT,
StockQuantity INT,
Description NVARCHAR(MAX),
ImagePath NVARCHAR(255)
)
GO
CREATE TABLE Users
(
Id INT PRIMARY KEY IDENTITY(1,1),
RoleName NVARCHAR(50),
FullName NVARCHAR(200),
Login NVARCHAR(100),
Password NVARCHAR(100)
)
GO
CREATE TABLE PickupPoints
(
Id INT PRIMARY KEY IDENTITY(1,1),
Address NVARCHAR(255)
)
GO
CREATE TABLE Orders
(
Id INT PRIMARY KEY IDENTITY(1,1),
OrderNumber NVARCHAR(50),
ProductArticle NVARCHAR(50),
OrderDate DATE,
DeliveryDate DATE,
PickupPointId INT,
ClientName NVARCHAR(200),
ReceiveCode NVARCHAR(50),
StatusName NVARCHAR(50),
FOREIGN KEY (PickupPointId)
REFERENCES PickupPoints(Id)
)
GO
Класс базы данных Data
using Microsoft.EntityFrameworkCore;
using ShoesApp.Models;
using System.Windows.Controls;
namespace ShoesApp.Data
{
public class AppDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<PickupPoint> PickupPoints { get; set; }
protected override void OnConfiguring(
DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
@"Server= DESKTOP-H4SR32G\SQLEXPRESS;
Database=ShoesDB;
Trusted_Connection=True;
TrustServerCertificate=True");
}
}
}
Класс базы данных Models
using System;
namespace ShoesApp.Models
{
public class Order
{
public int Id { get; set; }
public string OrderNumber { get; set; }
public string ProductArticle { get; set; }
public DateTime OrderDate { get; set; }
public DateTime DeliveryDate { get; set; }
public int PickupPointId { get; set; }
public string ClientName { get; set; }
public string ReceiveCode { get; set; }
public string StatusName { get; set; }
}
}
namespace ShoesApp.Models
{
public class PickupPoint
{
public int Id { get; set; }
public string Address { get; set; }
}
}
namespace ShoesApp.Models
{
public class Product
{
public int Id { get; set; }
public string Article { get; set; }
public string BrandName { get; set; }
public string Unit { get; set; }
public decimal Price { get; set; }
public int Discount { get; set; }
public int StockQuantity { get; set; }
public string Supplier { get; set; }
public string Manufacturer { get; set; }
public string Category { get; set; }
public string Description { get; set; }
public string ImagePath { get; set; }
public decimal FinalPrice
{
get
{
return Price - (Price * Discount / 100);
}
}
// Скидка больше 15%
public bool HasBigDiscount
{
get
{
return Discount > 15;
}
}
}
}
namespace ShoesApp.Models
{
public class User
{
public int Id { get; set; }
public string RoleName { get; set; }
public string FullName { get; set; }
public string Login { get; set; }
public string Password { get; set; }
}
}
Авторизация
<Window x:Class="ShoesApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Авторизация"
Height="300"
Width="400"
Background="White"
FontFamily="Times New Roman"
Icon="Resources/Icon.ico">
<Grid>
<StackPanel Width="200"
VerticalAlignment="Center">
<TextBlock Text="Логин"/>
<TextBox x:Name="txtLogin"
Margin="0 5 0 10"/>
<TextBlock Text="Пароль"/>
<PasswordBox x:Name="txtPassword"
Margin="0 5 0 10"/>
<Button Content="Войти"
Height="30"
Margin="0 0 0 10"
Background="#00FA9A"
Click="BtnLogin_Click"/>
<Button Content="Войти как гость"
Height="30"
Click="BtnGuest_Click"/>
</StackPanel>
</Grid>
</Window>
using ShoesApp.Data;
using ShoesApp.Models;
using System.Linq;
using System.Windows;
namespace ShoesApp
{
public partial class MainWindow : Window
{
AppDbContext db = new AppDbContext();
public MainWindow()
{
InitializeComponent();
}
private void BtnLogin_Click(
object sender,
RoutedEventArgs e)
{
User user = db.Users.FirstOrDefault(x =>
x.Login == txtLogin.Text &&
x.Password == txtPassword.Password);
if (user == null)
{
MessageBox.Show(
"Неверный логин или пароль");
return;
}
ProductsWindow window =
new ProductsWindow(user);
window.Show();
Close();
}
private void BtnGuest_Click(
object sender,
RoutedEventArgs e)
{
ProductsWindow window =
new ProductsWindow(null);
window.Show();
Close();
Страница Товаров
<Window x:Class="ShoesApp.ProductsWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Список товаров"
Height="700"
Width="1200"
Background="White"
FontFamily="Times New Roman"
Icon="Resources/Icon.ico">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<!-- Верх -->
<DockPanel Margin="0 0 0 10">
<!-- Логотип -->
<Image Source="Resources/Icon.png"
Width="80"
Height="80"
Stretch="Uniform"
DockPanel.Dock="Left"/>
<!-- ФИО -->
<TextBlock x:Name="txtUser"
FontSize="18"
FontWeight="Bold"
VerticalAlignment="Center"
Margin="20 0 0 0"/>
<!-- Выход -->
<Button Content="Выход"
Width="100"
Height="30"
Margin="20 0 0 0"
Background="#00FA9A"
Click="BtnExit_Click"/>
</DockPanel>
<!-- Панель -->
<StackPanel x:Name="PanelTools"
Grid.Row="1"
Orientation="Horizontal"
Margin="0 0 0 10">
<!-- Поиск -->
<StackPanel Orientation="Horizontal" Margin="0 0 0 10">
<StackPanel Margin="0 0 10 0">
<TextBlock Text="Артикул"/>
<TextBox x:Name="txtSearchArticle"
Width="150"
TextChanged="SearchChanged"/>
</StackPanel>
<StackPanel Margin="0 0 10 0">
<TextBlock Text="Категория"/>
<TextBox x:Name="txtSearchCategory"
Width="150"
TextChanged="SearchChanged"/>
</StackPanel>
<StackPanel Margin="0 0 10 0">
<TextBlock Text="Поставщик"/>
<TextBox x:Name="txtSearchSupplier"
Width="150"
TextChanged="SearchChanged"/>
</StackPanel>
</StackPanel>
<!-- Фильтр -->
<ComboBox x:Name="cmbSupplier"
Width="200"
Height="30"
Margin="0 0 10 0"
SelectionChanged="cmbSupplier_SelectionChanged"/>
<!-- Сортировка -->
<ComboBox x:Name="cmbSort"
Width="200"
Height="30"
Margin="0 0 10 0"
SelectionChanged="cmbSort_SelectionChanged">
<ComboBoxItem Content="Без сортировки"/>
<ComboBoxItem Content="По возрастанию"/>
<ComboBoxItem Content="По убыванию"/>
</ComboBox>
<!-- Добавить -->
<Button x:Name="btnAdd"
Content="Добавить"
Width="120"
Height="30"
Margin="0 0 10 0"
Background="#00FA9A"
Click="btnAdd_Click"/>
<!-- Заказы -->
<Button x:Name="btnOrders"
Content="Заказы"
Width="120"
Height="30"
Background="#00FA9A"
Click="btnOrders_Click"/>
</StackPanel>
<!-- Список -->
<ScrollViewer Grid.Row="2">
<ItemsControl x:Name="ProductsList">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black"
BorderThickness="1"
Margin="5"
Padding="5">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Background"
Value="White"/>
<Style.Triggers>
<!-- Скидка больше 15% -->
<DataTrigger Binding="{Binding HasBigDiscount}"
Value="True">
<Setter Property="Background"
Value="#2E8B57"/>
</DataTrigger>
<!-- Нет на складе -->
<DataTrigger Binding="{Binding StockQuantity}"
Value="0">
<Setter Property="Background"
Value="LightBlue"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions>
<!-- Фото -->
<Image Source="{Binding ImagePath}"
Width="100"
Height="100"
Stretch="Uniform"/>
<!-- Информация -->
<StackPanel Grid.Column="1"
Margin="10">
<TextBlock Text="{Binding Article}"
FontWeight="Bold"
FontSize="16"/>
<TextBlock Text="{Binding Category}"/>
<TextBlock Text="{Binding Description}"
TextWrapping="Wrap"/>
<TextBlock Text="{Binding Manufacturer,
StringFormat=Производитель: {0}}"/>
<TextBlock Text="{Binding Supplier,
StringFormat=Поставщик: {0}}"/>
<TextBlock Text="{Binding Unit,
StringFormat=Ед. изм.: {0}}"/>
<TextBlock Text="{Binding StockQuantity,
StringFormat=Остаток: {0}}"/>
<TextBlock Text="{Binding Price,
StringFormat=Цена: {0} ₽}"
Foreground="Red"
TextDecorations="Strikethrough"/>
<TextBlock Text="{Binding FinalPrice,
StringFormat=Со скидкой: {0} ₽}"
FontWeight="Bold"/>
</StackPanel>
<!-- Правая часть -->
<StackPanel Grid.Column="2"
VerticalAlignment="Center">
<TextBlock Text="{Binding Discount,
StringFormat=Скидка {0}%}"
FontSize="18"
FontWeight="Bold"
HorizontalAlignment="Center"/>
<Button Content="Редактировать"
Tag="{Binding Id}"
Click="BtnEdit_Click"
Visibility="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=Tag}"/>
<Button Content="Удалить"
Tag="{Binding Id}"
Click="BtnDelete_Click"
Visibility="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=Tag}"/>
</StackPanel>
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</Window>
using Microsoft.EntityFrameworkCore;
using ShoesApp.Data;
using ShoesApp.Models;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace ShoesApp
{
public partial class ProductsWindow : Window
{
AppDbContext db = new AppDbContext();
User currentUser;
public ProductsWindow(User user)
{
InitializeComponent();
currentUser = user;
Tag = (currentUser != null &&
currentUser.RoleName == "Администратор")
? Visibility.Visible
: Visibility.Collapsed;
txtUser.Text =
currentUser == null
? "Гость"
: currentUser.FullName;
LoadProducts();
CheckRole();
}
private void CheckRole()
{
// По умолчанию
btnAdd.Visibility =
Visibility.Collapsed;
btnOrders.Visibility =
Visibility.Collapsed;
// Гость
if (currentUser == null)
{
PanelTools.Visibility =
Visibility.Collapsed;
return;
}
// Авторизованный клиент
if (currentUser.RoleName ==
"Авторизированный клиент")
{
PanelTools.Visibility =
Visibility.Collapsed;
return;
}
// Менеджер
if (currentUser.RoleName ==
"Менеджер")
{
btnOrders.Visibility =
Visibility.Visible;
return;
}
// Администратор
if (currentUser.RoleName ==
"Администратор")
{
btnAdd.Visibility =
Visibility.Visible;
btnOrders.Visibility =
Visibility.Visible;
}
}
private void LoadProducts()
{
var products = db.Products.AsNoTracking().ToList();
foreach (var p in products)
{
if (string.IsNullOrEmpty(p.ImagePath))
p.ImagePath = "Images/picture.png";
}
ProductsList.ItemsSource = null;
ProductsList.ItemsSource = products;
cmbSupplier.Items.Clear();
cmbSupplier.Items.Add("Все поставщики");
foreach (var supplier in db.Products.Select(x => x.Supplier).Distinct())
cmbSupplier.Items.Add(supplier);
cmbSupplier.SelectedIndex = 0;
}
private void BtnDelete_Click(
object sender,
RoutedEventArgs e)
{
if (MessageBox.Show(
"Удалить товар?",
"Подтверждение",
MessageBoxButton.YesNo)
!= MessageBoxResult.Yes)
{
return;
}
int id =
(int)((Button)sender).Tag;
Product product =
db.Products
.FirstOrDefault(x => x.Id == id);
if (product != null)
{
db.Products.Remove(product);
db.SaveChanges();
LoadProducts();
}
}
private void BtnEdit_Click(
object sender,
RoutedEventArgs e)
{
Button button = (Button)sender;
int id = (int)button.Tag;
EditProductWindow window =
new EditProductWindow(id);
if (window.ShowDialog() == true)
{
LoadProducts();
}
}
private void BtnExit_Click(
object sender,
RoutedEventArgs e)
{
LoginWindow window =
new LoginWindow();
window.Show();
Close();
}
private void btnAdd_Click(
object sender,
RoutedEventArgs e)
{
AddProductWindow window =
new AddProductWindow();
window.ShowDialog();
LoadProducts();
}
private void btnOrders_Click(object sender, RoutedEventArgs e)
{
OrdersWindow window = new OrdersWindow(currentUser); // ← передай currentUser!
window.ShowDialog();
}
private void txtSearch_TextChanged(
object sender,
TextChangedEventArgs e)
{
FilterProducts();
}
private void cmbSupplier_SelectionChanged(
object sender,
SelectionChangedEventArgs e)
{
FilterProducts();
}
private void SearchChanged(object sender, TextChangedEventArgs e)
{
string article = txtSearchArticle.Text.ToLower();
string category = txtSearchCategory.Text.ToLower();
string supplier = txtSearchSupplier.Text.ToLower();
ProductsList.ItemsSource = db.Products
.Where(p =>
(p.Article ?? "").ToLower().Contains(article) &&
(p.Category ?? "").ToLower().Contains(category) &&
(p.Supplier ?? "").ToLower().Contains(supplier))
.ToList();
}
private void cmbSort_SelectionChanged(
object sender,
SelectionChangedEventArgs e)
{
FilterProducts();
}
private void FilterProducts()
{
var list = db.Products.ToList();
foreach (var p in list)
{
if (string.IsNullOrEmpty(p.ImagePath))
{
p.ImagePath = "Images/picture.png";
}
}
// Фильтр
if (cmbSupplier.SelectedIndex > 0)
{
string supplier =
cmbSupplier.SelectedItem.ToString();
list = list.Where(x =>
x.Supplier == supplier)
.ToList();
}
// Сортировка
if (cmbSort.SelectedIndex == 1)
{
list = list.OrderBy(x =>
x.StockQuantity)
.ToList();
}
if (cmbSort.SelectedIndex == 2)
{
list = list.OrderByDescending(x =>
x.StockQuantity)
.ToList();
}
ProductsList.ItemsSource = list;
}
}
}
Редактирование товара
<Window x:Class="ShoesApp.EditProductWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Редактирование товара"
Height="600"
Width="400"
FontFamily="Times New Roman"
Icon="Resources/Icon.ico">
<ScrollViewer>
<StackPanel Margin="10">
<TextBlock Text="Наименование"/>
<TextBox x:Name="txtArticle"/>
<TextBlock Text="Категория"/>
<TextBox x:Name="txtCategory"/>
<TextBlock Text="Описание"/>
<TextBox x:Name="txtDescription"/>
<TextBlock Text="Производитель"/>
<TextBox x:Name="txtManufacturer"/>
<TextBlock Text="Поставщик"/>
<TextBox x:Name="txtSupplier"/>
<TextBlock Text="Цена"/>
<TextBox x:Name="txtPrice"/>
<TextBlock Text="Единица"/>
<TextBox x:Name="txtUnit"/>
<TextBlock Text="Количество"/>
<TextBox x:Name="txtStock"/>
<TextBlock Text="Скидка"/>
<TextBox x:Name="txtDiscount"/>
<TextBlock Text="Изображение"/>
<StackPanel Orientation="Horizontal">
<TextBox x:Name="txtImage" Width="250"/>
<Button Content="..." Width="30" Margin="5 0 0 0" Click="BtnBrowse_Click"/>
</StackPanel>
<Button Content="Сохранить"
Height="35"
Margin="0 10 0 0"
Click="BtnSave_Click"/>
</StackPanel>
</ScrollViewer>
</Window>
using ShoesApp.Data;
using ShoesApp.Models;
using System.Linq;
using System.Windows;
namespace ShoesApp
{
public partial class EditProductWindow : Window
{
AppDbContext db =
new AppDbContext();
Product product;
private void BtnSave_Click(
object sender,
RoutedEventArgs e)
{
try
{
product.Article =
txtArticle.Text;
product.Category =
txtCategory.Text;
product.Description =
txtDescription.Text;
product.Manufacturer =
txtManufacturer.Text;
product.Supplier =
txtSupplier.Text;
product.Price =
decimal.Parse(txtPrice.Text);
product.Unit =
txtUnit.Text;
product.StockQuantity =
int.Parse(txtStock.Text);
product.Discount =
int.Parse(txtDiscount.Text);
product.ImagePath =
string.IsNullOrWhiteSpace(txtImage.Text)
? "Images/picture.png"
: txtImage.Text;
db.SaveChanges();
MessageBox.Show(
"Товар изменен");
Close();
}
catch
{
MessageBox.Show(
"Ошибка сохранения");
}
}
private void BtnBrowse_Click(
object sender,
RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dialog =
new Microsoft.Win32.OpenFileDialog();
dialog.Filter =
"Изображения|*.jpg;*.jpeg;*.png";
if (dialog.ShowDialog() == true)
{
txtImage.Text =
dialog.FileName;
}
}
public EditProductWindow(int id)
{
InitializeComponent();
product =
db.Products
.FirstOrDefault(x => x.Id == id);
txtArticle.Text =
product.Article;
txtCategory.Text =
product.Category;
txtDescription.Text =
product.Description;
txtManufacturer.Text =
product.Manufacturer;
txtSupplier.Text =
product.Supplier;
txtPrice.Text =
product.Price.ToString();
txtUnit.Text =
product.Unit;
txtStock.Text =
product.StockQuantity.ToString();
txtDiscount.Text =
product.Discount.ToString();
txtImage.Text =
product.ImagePath;
}
}
}
Добавление товара
<Window x:Class="ShoesApp.AddProductWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Добавление товара"
Height="600"
Width="400"
Background="White"
FontFamily="Times New Roman"
Icon="Resources/Icon.ico">
<ScrollViewer>
<StackPanel Margin="20">
<TextBlock Text="Наименование"/>
<TextBox x:Name="txtArticle"/>
<TextBlock Text="Категория"/>
<TextBox x:Name="txtCategory"/>
<TextBlock Text="Описание"/>
<TextBox x:Name="txtDescription"/>
<TextBlock Text="Производитель"/>
<TextBox x:Name="txtManufacturer"/>
<TextBlock Text="Поставщик"/>
<TextBox x:Name="txtSupplier"/>
<TextBlock Text="Цена"/>
<TextBox x:Name="txtPrice"/>
<TextBlock Text="Единица"/>
<TextBox x:Name="txtUnit"/>
<TextBlock Text="Количество"/>
<TextBox x:Name="txtStock"/>
<TextBlock Text="Скидка"/>
<TextBox x:Name="txtDiscount"/>
<TextBlock Text="Путь к фото"/>
<TextBox x:Name="txtImage"/>
<Button Content="Выбрать фото"
Height="30"
Margin="0 5 0 0"
Click="BtnImage_Click"/>
<Button Content="Сохранить"
Height="35"
Margin="0 20 0 0"
Background="#00FA9A"
Click="BtnSave_Click"/>
</StackPanel>
</ScrollViewer>
</Window>
using Microsoft.Win32;
using ShoesApp.Data;
using ShoesApp.Models;
using System;
using System.Collections.Generic;
using System.IO;
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;
namespace ShoesApp
{
public partial class AddProductWindow : Window
{
AppDbContext db = new AppDbContext();
public AddProductWindow()
{
InitializeComponent();
}
private void BtnImage_Click(
object sender,
RoutedEventArgs e)
{
OpenFileDialog dialog =
new OpenFileDialog();
dialog.Filter =
"Изображения|*.jpg;*.jpeg;*.png";
if (dialog.ShowDialog() == true)
{
txtImage.Text =
dialog.FileName;
}
}
private void BtnSave_Click(
object sender,
RoutedEventArgs e)
{
try
{
Product product =
new Product();
product.Article =
txtArticle.Text;
product.Category =
txtCategory.Text;
product.Description =
txtDescription.Text;
product.Manufacturer =
txtManufacturer.Text;
product.Supplier =
txtSupplier.Text;
product.Price =
decimal.Parse(txtPrice.Text);
product.Unit =
txtUnit.Text;
product.StockQuantity =
int.Parse(txtStock.Text);
product.Discount =
int.Parse(txtDiscount.Text);
product.ImagePath =
string.IsNullOrWhiteSpace(txtImage.Text)
? "Images/picture.png"
: txtImage.Text;
db.Products.Add(product);
db.SaveChanges();
MessageBox.Show(
"Товар добавлен",
"Информация",
MessageBoxButton.OK,
MessageBoxImage.Information);
Close();
}
catch
{
MessageBox.Show(
"Ошибка при добавлении товара",
"Ошибка",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
}
}
Страница заказов
<Window x:Class="ShoesApp.OrdersWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Заказы"
Height="600"
Width="1000"
Background="White"
FontFamily="Times New Roman"
Icon="Resources/Icon.ico">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Margin="0 0 0 10">
<Button x:Name="btnAdd"
Content="Добавить"
Width="120"
Margin="0 0 10 0"
Click="BtnAdd_Click"/>
<Button Content="Назад"
Width="120"
Click="BtnBack_Click"/>
</StackPanel>
<ScrollViewer Grid.Row="1">
<ItemsControl x:Name="OrdersList">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black"
BorderThickness="1"
Margin="5"
Padding="10">
<StackPanel>
<TextBlock Text="{Binding ProductArticle, StringFormat=Артикул: {0}}"/>
<TextBlock Text="{Binding StatusName, StringFormat=Статус: {0}}"/>
<TextBlock Text="{Binding PickupPointAddress, StringFormat=Пункт: {0}}"/>
<TextBlock Text="{Binding OrderDate, StringFormat=Дата: {0:d}}"/>
<TextBlock Text="{Binding DeliveryDate, StringFormat=Доставка: {0:d}}"/>
<Button Content="Редактировать"
Tag="{Binding Id}"
Click="BtnEdit_Click"
Visibility="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=Tag}"/>
<Button Content="Удалить"
Tag="{Binding Id}"
Click="BtnDelete_Click"
Visibility="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=Tag}"/>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</Window>
using Microsoft.EntityFrameworkCore;
using ShoesApp.Data;
using ShoesApp.Models;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace ShoesApp
{
public partial class OrdersWindow : Window
{
AppDbContext db = new AppDbContext();
User currentUser;
public OrdersWindow(User user = null)
{
InitializeComponent();
currentUser = user;
Tag = (currentUser != null &&
currentUser.RoleName == "Администратор")
? Visibility.Visible
: Visibility.Collapsed;
CheckRole();
LoadOrders();
}
private void CheckRole()
{
btnAdd.Visibility = Visibility.Collapsed;
if (currentUser == null)
return;
if (currentUser.RoleName == "Администратор")
btnAdd.Visibility = Visibility.Visible;
}
private void LoadOrders()
{
var orders = db.Orders
.Join(db.PickupPoints,
o => o.PickupPointId,
p => p.Id,
(o, p) => new
{
o.Id,
o.ProductArticle,
o.StatusName,
o.OrderDate,
o.DeliveryDate,
PickupPointAddress = p.Address
})
.ToList();
OrdersList.ItemsSource = orders;
}
private void BtnAdd_Click(object sender, RoutedEventArgs e)
{
new AddOrderWindow().ShowDialog();
LoadOrders();
}
private void BtnEdit_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
int id = (int)button.Tag;
new EditOrderWindow(id).ShowDialog();
LoadOrders();
}
private void BtnDelete_Click(object sender, RoutedEventArgs e)
{
if (MessageBox.Show("Удалить заказ?", "Подтверждение",
MessageBoxButton.YesNo) != MessageBoxResult.Yes)
return;
int id = (int)((Button)sender).Tag;
var order = db.Orders.FirstOrDefault(x => x.Id == id);
if (order != null)
{
db.Orders.Remove(order);
db.SaveChanges();
LoadOrders();
}
}
private void BtnBack_Click(object sender, RoutedEventArgs e)
{
Close();
}
}
}
Добавить заказ
<Window x:Class="ShoesApp.AddOrderWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Добавить заказ"
Height="350"
Width="400"
Icon="Resources/Icon.ico">
<StackPanel Margin="10">
<TextBlock Text="Артикул"/>
<TextBox x:Name="txtArticle"/>
<TextBlock Text="Статус"/>
<TextBox x:Name="txtStatus"/>
<TextBlock Text="Пункт (ID)"/>
<TextBox x:Name="txtPickup"/>
<Button Content="Сохранить"
Click="BtnSave_Click"/>
</StackPanel>
</Window>
using ShoesApp.Data;
using ShoesApp.Models;
using System;
using System.Windows;
namespace ShoesApp
{
public partial class AddOrderWindow : Window
{
AppDbContext db = new AppDbContext();
public AddOrderWindow()
{
InitializeComponent();
}
private void BtnSave_Click(object sender, RoutedEventArgs e)
{
db.Orders.Add(new Order
{
ProductArticle = txtArticle.Text,
StatusName = txtStatus.Text,
PickupPointId = int.Parse(txtPickup.Text),
OrderDate = DateTime.Now,
DeliveryDate = DateTime.Now.AddDays(3)
});
db.SaveChanges();
Close();
}
}
}
Редактировать Заказа
<Window x:Class="ShoesApp.EditOrderWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Редактировать заказ"
Height="300"
Width="400"
Icon="Resources/Icon.ico">
<StackPanel Margin="10">
<TextBlock Text="Артикул"/>
<TextBox x:Name="txtArticle"/>
<TextBlock Text="Статус"/>
<TextBox x:Name="txtStatus"/>
<TextBlock Text="Пункт (ID)"/>
<TextBox x:Name="txtPickup"/>
<Button Content="Сохранить"
Click="BtnSave_Click"/>
</StackPanel>
</Window>
using ShoesApp.Data;
using ShoesApp.Models;
using System.Linq;
using System.Windows;
namespace ShoesApp
{
public partial class EditOrderWindow : Window
{
AppDbContext db = new AppDbContext();
Order order;
public EditOrderWindow(int id)
{
InitializeComponent();
order = db.Orders.First(x => x.Id == id);
txtArticle.Text = order.ProductArticle;
txtStatus.Text = order.StatusName;
txtPickup.Text = order.PickupPointId.ToString();
}
private void BtnSave_Click(object sender, RoutedEventArgs e)
{
order.ProductArticle = txtArticle.Text;
order.StatusName = txtStatus.Text;
order.PickupPointId = int.Parse(txtPickup.Text);
db.SaveChanges();
Close();
}
}
}