Demka/Demka-2/Views/MainWindow.axaml.cs
2024-12-27 11:59:46 +03:00

107 lines
3.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using System.Collections.ObjectModel;
using System.Linq;
using Demka_2.Use;
using System;
namespace Demka_2.Views;
public partial class MainWindow : Window
{
private ObservableCollection<Service> Services { get; set; } = new ObservableCollection<Service>();
private ObservableCollection<Service> FilteredServices { get; set; } = new ObservableCollection<Service>();
private TextBox _searchBox;
private ComboBox _discountFilter;
private ListBox _serviceList;
private TextBlock _serviceCountText;
public MainWindow()
{
InitializeComponent();
LoadServices();
UpdateFilteredServices();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
_searchBox = this.FindControl<TextBox>("SearchBox");
_discountFilter = this.FindControl<ComboBox>("DiscountFilter");
_serviceList = this.FindControl<ListBox>("ServiceList");
_serviceCountText = this.FindControl<TextBlock>("ServiceCountText");
_serviceList.ItemsSource = FilteredServices;
_searchBox.TextChanged += SearchBox_TextChanged;
_discountFilter.SelectionChanged += DiscountFilter_SelectionChanged;
}
private void LoadServices()
{
using (var context = new AppDbContext())
{
var services = context.Services.ToList();
foreach (var service in services)
{
Services.Add(service);
}
}
}
private void UpdateFilteredServices()
{
var query = Services.AsEnumerable();
if (!string.IsNullOrWhiteSpace(_searchBox.Text))
{
string searchQuery = _searchBox.Text.ToLower();
query = query.Where(service =>
service.Name.ToLower().Contains(searchQuery) ||
service.Description.ToLower().Contains(searchQuery));
}
if (_discountFilter.SelectedItem is TextBlock selected && selected.Text != "Все")
{
var range = ParseDiscountRange(selected.Text);
if (range != null)
{
query = query.Where(service =>
service.Discount >= range.Value.min && service.Discount < range.Value.max);
}
}
FilteredServices.Clear();
foreach (var service in query)
{
FilteredServices.Add(service);
}
_serviceCountText.Text = $"{FilteredServices.Count} из {Services.Count}";
}
private void SearchBox_TextChanged(object? sender, EventArgs e)
{
UpdateFilteredServices();
}
private void DiscountFilter_SelectionChanged(object? sender, SelectionChangedEventArgs e)
{
UpdateFilteredServices();
}
private (decimal min, decimal max)? ParseDiscountRange(string rangeText)
{
return rangeText switch
{
"0-5%" => (0, 5),
"5-15%" => (5, 15),
"15-30%" => (15, 30),
"30-70%" => (30, 70),
"70-100%" => (70, 100),
_ => null,
};
}
}