Я создаю этот интернет-магазин в WPF как часть одного из моих заданий по программированию, где у меня есть страница игр, на которой отображаются все игры. Я использовал DataGrid, который также имеет DataTemplate с RowDefinitions, чтобы при щелчке строки он расширялся и отображал больше информации об игре, на которую вы щелкнули. Я в основном использовал текстовые блоки, чтобы показать, чтобы отобразить содержимое в передней части. Все элементы управления переднего плана имеют привязку данных к списку объектов, называемых «игры», в моем файле .cs, где я вручную добавил детали для нескольких игр, чтобы протестировать их (сейчас повторяется та же самая игра, пока я тестирование).
Моя проблема в том, что мне нужно заполнить содержимое этого списка объектов из базы данных, и я понятия не имею, как этого добиться, идея в том, что вы можете изменить количество игр в базе данных, и вы сможете увидеть это в таблице данных на странице игр (например, если вы выполните запрос и добавите еще 2 игры в таблицу БД, у вас также будет еще 2 игры, отображенные в DataGrid ). Я рассмотрел несколько вещей, чтобы заполнить этот список, таких как использование таблицы данных или просто создание гиганта для l oop, чтобы сделать это для вас, но, насколько я понимаю, до тех пор, пока я это понимаю и это работает, любое решение более чем приветствуется.
Вот как это выглядит в настоящее время с данными, которые я хранил в списке вручную. С точки зрения того, как это выглядит, это желаемый результат. Мне просто нужно, чтобы все эти данные, которые он получает через DataBinding из списка, были из базы данных, а не добавлены мной вручную в файл .cs. Не беспокойтесь об изображении, так как оно загружается с URL-адреса, и я уверен, что, как только я пойму, как заполнить этот список из БД, я тоже смогу добавлять изображения из БД.
Вот код XAML для внешнего интерфейса.
<Page xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit" x:Class="RareMantis.GamesPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:RareMantis"
mc:Ignorable="d"
d:DesignHeight="534" d:DesignWidth="1200"
Title="GamesPage"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
TextElement.Foreground="{DynamicResource MaterialDesignBody}"
TextElement.FontWeight="Regular"
TextElement.FontSize="13"
TextOptions.TextFormattingMode="Ideal"
TextOptions.TextRenderingMode="Auto"
Background="{DynamicResource MaterialDesignPaper}"
FontFamily="{DynamicResource MaterialDesignFont}">
<!--Main Grid used for setting blue background-->
<Grid Background="#374e70">
<!--Second grid with page content-->
<Grid>
<!--Declare Rows-->
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--Declare Columns-->
<Grid.ColumnDefinitions>
<ColumnDefinition Width="170"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!--Grid containing Page Title-->
<Grid Grid.RowSpan="2">
<TextBlock Text="Games" HorizontalAlignment="Center" Margin="10" FontSize="28"/>
</Grid>
<!--Page content is placed withing a stackpanel (+scrollviewer)-->
<ScrollViewer Grid.Column="1" Grid.Row="1" Background="#FFF1F1F1">
<StackPanel>
<!--Catalogue Text-->
<TextBlock Text="Catalogue" Margin="10" FontSize="22" FontWeight="Medium"/>
<!--Datagrid containig the table with rows and columns-->
<DataGrid Name="dg_Games" AutoGenerateColumns="False">
<!--Declare the main columns that get displayed initially and bind data from "Game class"-->
<DataGrid.Columns>
<DataGridTextColumn Header="Title" Binding="{Binding Title}" />
<DataGridTextColumn Header="Genre" Binding="{Binding Genre}" />
<DataGridTextColumn Header="Release Date" Binding="{Binding Release}" />
<DataGridTextColumn Header="Price £" Binding="{Binding Price}" />
</DataGrid.Columns>
<!--Declare the details contained by the rows(when you click them and they expand)-->
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<!--Dockpanel for expanding the row-->
<DockPanel Background="GhostWhite">
<Image DockPanel.Dock="Left" Source="{Binding ImageUrl}" Height="64" Margin="10" />
<!--Grid for row dockpanel content-->
<Grid Margin="0,10">
<!--Declare 2 Columns-->
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<!--Declare 4 Rows-->
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!--Game Image from class-->
<TextBlock Text="" FontWeight="Bold" />
<TextBlock Text="{Binding GameImage}" Grid.Column="1" />
<!--Developer name from class-->
<TextBlock Text="Developer: " FontWeight="Bold" Grid.Row="1" />
<TextBlock Text="{Binding Developer}" Grid.Column="1" Grid.Row="1" />
<!--Description from class-->
<TextBlock Text="Description: " FontWeight="Bold" Grid.Row="2" />
<TextBlock Grid.Column="1" Grid.Row="3" Width="300" HorizontalAlignment="Left" Text="{Binding Description}" TextWrapping="WrapWithOverflow"/>
<!--Purchase button-->
<Button x:Name="btn_Purchase" Grid.Column="1" Grid.Row="3" Width="100" Click="btn_Purchase_Click" Content="Purchase" />
</Grid>
</DockPanel>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
</StackPanel>
</ScrollViewer>
</Grid>
</Grid>
</Page>
Это код C# из файла .cs.
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.Navigation;
using System.Windows.Shapes;
//add namespace
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace RareMantis
{
/// <summary>
/// Interaction logic for GamesPage.xaml
/// </summary>
public partial class GamesPage : Page
{
public GamesPage()
{
InitializeComponent();
//Make List based on object items
List<Game> games = new List<Game>();
//Add games manally via "Games" class
games.Add(new Game() { GameID = 1, ImageUrl = "https://www.freepnglogos.com/uploads/gta-5-logo-png/grand-theft-auto-v-1.png", Title = "GTA 5", Genre = "Action-adventure, Open world", Description = "Grand Theft Auto V for PC offers players the option to explore the award-winning world of Los Santos and Blaine County in resolutions of up to 4k and beyond, as well as the chance to experience the game running at 60 frames per second.", Developer = "Rockstar North", Release = new DateTime(2013, 10, 4), Price = "59.99" });
games.Add(new Game() { GameID = 2, ImageUrl = "https://www.freepnglogos.com/uploads/gta-5-logo-png/grand-theft-auto-v-1.png", Title = "GTA 5", Genre = "Action-adventure, Open world", Description = "Grand Theft Auto V for PC offers players the option to explore the award-winning world of Los Santos and Blaine County in resolutions of up to 4k and beyond, as well as the chance to experience the game running at 60 frames per second.", Developer = "Rockstar North", Release = new DateTime(2013, 10, 4), Price = "59.99" });
games.Add(new Game() { GameID = 3, ImageUrl = "https://www.freepnglogos.com/uploads/gta-5-logo-png/grand-theft-auto-v-1.png", Title = "GTA 5", Genre = "Action-adventure, Open world", Description = "Grand Theft Auto V for PC offers players the option to explore the award-winning world of Los Santos and Blaine County in resolutions of up to 4k and beyond, as well as the chance to experience the game running at 60 frames per second.", Developer = "Rockstar North", Release = new DateTime(2013, 10, 4), Price = "59.99" });
games.Add(new Game() { GameID = 4, ImageUrl = "https://www.freepnglogos.com/uploads/gta-5-logo-png/grand-theft-auto-v-1.png", Title = "GTA 5", Genre = "Action-adventure, Open world", Description = "Grand Theft Auto V for PC offers players the option to explore the award-winning world of Los Santos and Blaine County in resolutions of up to 4k and beyond, as well as the chance to experience the game running at 60 frames per second.", Developer = "Rockstar North", Release = new DateTime(2013, 10, 4), Price = "59.99" });
games.Add(new Game() { GameID = 5, ImageUrl = "https://www.freepnglogos.com/uploads/gta-5-logo-png/grand-theft-auto-v-1.png", Title = "GTA 5", Genre = "Action-adventure, Open world", Description = "Grand Theft Auto V for PC offers players the option to explore the award-winning world of Los Santos and Blaine County in resolutions of up to 4k and beyond, as well as the chance to experience the game running at 60 frames per second.", Developer = "Rockstar North", Release = new DateTime(2013, 10, 4), Price = "59.99" });
//Add to datagrid from "games list"
dg_Games.ItemsSource = games;
}
//Game class for database content on games page
public class Game
{
public int GameID { get; set; }
//Not used anymore
//public Image GameImage { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Genre { get; set; }
public string Developer { get; set; }
public DateTime Release { get; set; }
public string Price { get; set; }
//Temporary, don't worry about this
public string ImageUrl { get; set; }
}
//Button purchase click
private void btn_Purchase_Click(object sender, RoutedEventArgs e)
{
}
}
}
И, наконец, вот что мой Таблица в SSMS должна выглядеть так. Я еще не начал заполнять его, поскольку даже не знаю, как заполнить список.
![enter image description here](https://i.stack.imgur.com/jUxKJ.png)
РЕДАКТИРОВАТЬ: Я забыл добавить некоторые подробности о сторонних библиотеках, мое единственное реальное ограничение для этого заключается в том, что я должен использовать Entity Framework, но, кроме того, я могу использовать практически любую стороннюю библиотеку, если она с открытым исходным кодом.