Получение данных из внешних источников. JSON.
Class2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApp1.model
{
class Globals
{
public static IDataProvider dataProvider;
IEnumerable<ClientPrice> getClientPrice()
{
return new ClientPrice[] {
new ClientPrice{title="Все цены", PriceFrom=500, PriceTo=30000},
new ClientPrice{title="Низкая цена", PriceFrom=500, PriceTo=3000},
new ClientPrice{title="Средняя цена", PriceFrom=3000, PriceTo = 15000},
new ClientPrice{title="Высокая цена", PriceFrom=15000, PriceTo=30000},
};
}
IEnumerable<ClientCategory> getClientCategory()
{
return new ClientCategory[]
{
new ClientCategory { title = "По России" },
new ClientCategory { title = "За границей" },
};
}
}
}
Class3
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApp1.model
{
public class ClientPrice
{
public string title { get; set; }
public int PriceFrom { get; set; }
public int PriceTo { get; set; }
}
public class ClientCategory
{
public string title { get; set; }
}
}
Class4
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace WpfApp1.model
{
[DataContract]
public class Client
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public int Price { get; set; }
[DataMember]
public string Place { get; set; }
[DataMember]
public string Category { get; set; }
[DataMember]
public bool IsActive { get; set; }
[DataMember(Name = "DateFlight")]
private string? stringDate { get; set; }
[IgnoreDataMember]
public DateTime? DateFlight
{
get
{
return stringDate == null ? null : DateTime.Parse(stringDate);
}
set
{
stringDate = value.ToString();
}
}
}
}
MainWindow.xaml.cs
using System.ComponentModel;
using System.Text;
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.Navigation;
using System.Windows.Shapes;
using WpfApp1.model.WpfApp4.model;
using WpfApp1.model;
using System.IO;
using System.Runtime.Serialization.Json;
namespace WpfApp1
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void Invalidate()
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("ClientList"));
}
public string selectedCategory = "Все категории";
public ClientPrice? selectedPrice = null;
private IEnumerable<Client> _ClientList;
public IEnumerable<Client> ClientList
{
get
{
var res = _ClientList;
res = res
.Where(c => (selectedPrice == null || (c.Price >= selectedPrice.PriceFrom && c.Price < selectedPrice.PriceTo)))
.Where(c => (c.Category == selectedCategory || selectedCategory == "Все категории"));
if (searchFilter != "")
res = res.Where(c => c.Name.IndexOf(
searchFilter,
StringComparison.OrdinalIgnoreCase) >= 0 || c.Category.IndexOf(
searchFilter,
StringComparison.OrdinalIgnoreCase) >= 0 || c.Place.IndexOf(
searchFilter,
StringComparison.OrdinalIgnoreCase) >= 0);
if (sortAsc) res = res.OrderBy(c => c.Price);
else res = res.OrderByDescending(c => c.Price);
if (sortAsc) res = res.OrderBy(c => c.Price);
else res = res.OrderByDescending(c => c.Price);
return res;
}
set
{
_ClientList = value;
}
}
public List<Client> Client { get; set; }
public List<ClientCategory> ClientCategoryList { get; set; }
public List<ClientPrice> ClientPriceList { get; set; }
public MainWindow()
{
{
InitializeComponent();
DataContext = this;
Globals.dataProvider = new JSONDataProvider();
ClientList = Globals.dataProvider.getClient();
ClientPriceList = Globals.dataProvider.getPrice().ToList();
ClientCategoryList = Globals.dataProvider.getCategory().ToList();
ClientCategoryList.Insert(0, new ClientCategory() { title = "Все категории" });
}
}
public class JSONDataProvider: LocalDataProvider, IDataProvider
{
private List<Client> _ClientList;
public JSONDataProvider()
{
var serializer = new DataContractJsonSerializer(typeof(Client[]));
using (var sr = new StreamReader("./data.json"))
{
_ClientList = ((Client[])serializer.ReadObject(sr.BaseStream)).ToList();
}
}
public IEnumerable<Client> getClient()
{
return _ClientList;
}
}
private void ExitButton_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
private string searchFilter = "";
private void SearchFilter_KeyUp(object sender, KeyEventArgs e)
{
searchFilter = SearchFilterTextBox.Text;
Invalidate();
}
private void ClientCategoryFilterComboBox_selectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
selectedCategory = (CategoryFilterComboBox.SelectedItem as ClientCategory).title;
Invalidate();
}
private void ClientPriceFilterComboBox_selectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
selectedPrice = PriceFilterComboBox.SelectedItem as ClientPrice;
Invalidate();
}
private bool sortAsc = true;
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
sortAsc = (sender as RadioButton).Tag.ToString() == "1";
Invalidate();
}
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
}
interface IDataProvider
{
IEnumerable<Client> getClient();
IEnumerable<ClientPrice> getPrice();
IEnumerable<ClientCategory> getCategory();
}
public class LocalDataProvider : IDataProvider
{
public IEnumerable<ClientCategory> getCategory()
{
return new ClientCategory[]
{
new ClientCategory()
{
title="По России"
},
new ClientCategory()
{
title="За границей"
},
};
}
public IEnumerable<ClientPrice> getPrice()
{
return new ClientPrice[]
{
new ClientPrice()
{
title = "Все цены",
PriceFrom = 500,
PriceTo = 30000
},
new ClientPrice()
{
title = "Низкая цена",
PriceFrom = 500,
PriceTo = 3000
},
new ClientPrice()
{
title = "Средняя цена",
PriceFrom = 3000,
PriceTo = 15000
},
new ClientPrice()
{
title = "Высокая цена",
PriceFrom = 15000,
PriceTo = 30000
}
};
}
public IEnumerable<Client> getClient()
{
return new Client[]{
new Client{
Name = "Никита",
Age = 20,
Price=2300,
Category="По России",
Place="Москва"
},
new Client{
Name = "Маша",
Age = 15,
Price=5000,
Category="По России",
Place="Сочи"
},
new Client{
Name = "Алиса",
Age = 35,
Price=15000,
Category="За границей",
Place="Токио"
},
new Client{
Name = "Леша",
Age = 19,
Price=20000,
Category="За границей",
Place="Южная Корея"
},
new Client{
Name = "Андрей",
Age = 28,
Price=3000,
Category="По России",
Place="Крым"
},
new Client{
Name = "Костя",
Age = 14,
Price=18000,
Category="За границей",
Place="Токио"
},
new Client{
Name = "Даша",
Age = 12,
Price=25000,
Category="За границей",
Place="Лондон"
},
new Client{
Name = "Ольга",
Age = 55,
Price=22000,
Category="За границей",
Place="Люксембург"
},
new Client{
Name = "Катя",
Age = 30,
Price=1500,
Category="По России",
Place="Адлер"
},
new Client{
Name = "Анжела",
Age = 61,
Price=25000,
Category="За границей",
Place="Мальдивы"
},
new Client{
Name = "Миша",
Age = 17,
Price=30000,
Category="За границей",
Place="Дубаи"
},
};
}
}
}
data.json
[
{
"Name": "Никита",
"Age": 20,
"Price": 2300,
"Category": "По России",
"Place": "Москва",
"IsActive": true,
"DateFlight": "2024-12-20"
},
{
"Name": "Маша",
"Age": 15,
"Price": 5000,
"Category": "По России",
"Place": "Сочи",
"IsActive": false,
"DateFlight": "2024-06-14"
},
{
"Name": "Алиса",
"Age": 35,
"Price": 15000,
"Category": "За границей",
"Place": "Токио",
"IsActive": true,
"DateFlight": "2024-05-03"
},
{
"Name": "Леша",
"Age": 19,
"Price": 20000,
"Category": "За границей",
"Place": "Южная Корея",
"IsActive": false,
"DateFlight": "2024-11-18"
},
{
"Name": "Андрей",
"Age": 28,
"Price": 3000,
"Category": "По России",
"Place": "Крым",
"IsActive": true,
"DateFlight": "2024-07-27"
},
{
"Name": "Костя",
"Age": 14,
"Price": 18000,
"Category": "За границей",
"Place": "Токио",
"IsActive": false,
"DateFlight": "2024-08-08"
},
{
"Name": "Даша",
"Age": 12,
"Price": 25000,
"Category": "За границей",
"Place": "Лондон",
"IsActive": false,
"DateFlight": "2025-02-04"
},
{
"Name": "Ольга",
"Age": 55,
"Price": 22000,
"Category": "За границей",
"Place": "Люксембург",
"IsActive": false,
"DateFlight": "2024-09-01"
},
{
"Name": "Катя",
"Age": 30,
"Price": 1500,
"Category": "По России",
"Place": "Адлер",
"IsActive": true,
"DateFlight": "2024-10-31"
},
{
"Name": "Анжела",
"Age": 61,
"Price": 25000,
"Category": "За границей",
"Place": "мальдивы",
"IsActive": true,
"DateFlight": "2025-01-10"
},
{
"Name": "Миша",
"Age": 17,
"Price": 30000,
"Category": "За границей",
"Place": "Дубаи",
"IsActive": false,
"DateFlight": "2024-03-21"
}
]
MainWindow.xaml
<Window x:Class="WpfApp1.MainWindow"
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:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid ShowGridLines="True">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition />
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<!-- типа логотип компании -->
<Image
Source="/img/1.jpg"
Grid.RowSpan="2" HorizontalAlignment="Right"/>
<DataGrid
Grid.Row="1"
Grid.Column="1"
CanUserAddRows="False"
AutoGenerateColumns="False"
ItemsSource="{Binding ClientList}">
<DataGrid.Columns>
<DataGridTextColumn
Header="Имя"
Binding="{Binding Name}"/>
<DataGridTextColumn
Header="Возраст"
Binding="{Binding Age}"/>
<DataGridTextColumn
Header="Цена"
Binding="{Binding Price}"/>
<DataGridTextColumn
Header="Место"
Binding="{Binding Place}"/>
<DataGridTextColumn
Header="Категория"
Binding="{Binding Category}"/>
<DataGridTextColumn
Header="Дата полета"
Binding="{Binding DateFlight,StringFormat='dd.MM.yyyy'}"/>
<DataGridTextColumn
Header="IsActive"
Binding="{Binding IsActive}"/>
</DataGrid.Columns>
</DataGrid>
<StackPanel
Orientation="Vertical"
Grid.RowSpan="3"
VerticalAlignment="Bottom">
<Button
x:Name="ExitButton"
Content="Выход"
Click="ExitButton_Click"
Height="50"/>
</StackPanel>
<WrapPanel
Orientation="Horizontal"
Grid.Column="1"
MinHeight="50">
<Label
Content="Искать:"
VerticalAlignment="Center"/>
<TextBox
Width="200"
VerticalAlignment="Center"
x:Name="SearchFilterTextBox"
KeyUp="SearchFilter_KeyUp"/>
<ComboBox
Name="CategoryFilterComboBox"
SelectionChanged="ClientCategoryFilterComboBox_selectionChanged"
VerticalAlignment="Center"
MinWidth="100"
SelectedIndex="0"
ItemsSource="{Binding ClientCategoryList}">
<ComboBox.ItemTemplate>
<DataTemplate>
<Label
Content="{Binding title}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Label
Content="Цена:"
VerticalAlignment="Center"/>
<ComboBox
Name="PriceFilterComboBox"
SelectionChanged="ClientPriceFilterComboBox_selectionChanged"
VerticalAlignment="Center"
MinWidth="100"
SelectedIndex="0"
ItemsSource="{Binding ClientPriceList}">
<ComboBox.ItemTemplate>
<DataTemplate>
<Label
Content="{Binding title}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Label
Content="Возраст:"
VerticalAlignment="Center"/>
<RadioButton
GroupName="Age"
Tag="1"
Content="Сначала взрослые"
IsChecked="True"
Checked="RadioButton_Checked"
VerticalAlignment="Center"/>
<RadioButton
GroupName="Age"
Tag="2"
Content="Сначала дети"
Checked="RadioButton_Checked"
VerticalAlignment="Center"/>
<!-- минимальную высоту я тут поставил, чтобы верхнюю строку сетки было видно. В реальном приложении она не нужна -->
</WrapPanel>
</Grid>
</Window>