Jelajahi Sumber

Добавьте файлы проекта.

lyudmila.archackowa 8 bulan lalu
melakukan
bf7deb9ebb

+ 63 - 0
.gitattributes

@@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs     diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following 
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln       merge=binary
+#*.csproj    merge=binary
+#*.vbproj    merge=binary
+#*.vcxproj   merge=binary
+#*.vcproj    merge=binary
+#*.dbproj    merge=binary
+#*.fsproj    merge=binary
+#*.lsproj    merge=binary
+#*.wixproj   merge=binary
+#*.modelproj merge=binary
+#*.sqlproj   merge=binary
+#*.wwaproj   merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg   binary
+#*.png   binary
+#*.gif   binary
+
+###############################################################################
+# diff behavior for common document formats
+# 
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the 
+# entries below.
+###############################################################################
+#*.doc   diff=astextplain
+#*.DOC   diff=astextplain
+#*.docx  diff=astextplain
+#*.DOCX  diff=astextplain
+#*.dot   diff=astextplain
+#*.DOT   diff=astextplain
+#*.pdf   diff=astextplain
+#*.PDF   diff=astextplain
+#*.rtf   diff=astextplain
+#*.RTF   diff=astextplain

+ 363 - 0
.gitignore

@@ -0,0 +1,363 @@
+## Ignore Visual Studio temporary files, build results, and
+## files generated by popular Visual Studio add-ons.
+##
+## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
+
+# User-specific files
+*.rsuser
+*.suo
+*.user
+*.userosscache
+*.sln.docstates
+
+# User-specific files (MonoDevelop/Xamarin Studio)
+*.userprefs
+
+# Mono auto generated files
+mono_crash.*
+
+# Build results
+[Dd]ebug/
+[Dd]ebugPublic/
+[Rr]elease/
+[Rr]eleases/
+x64/
+x86/
+[Ww][Ii][Nn]32/
+[Aa][Rr][Mm]/
+[Aa][Rr][Mm]64/
+bld/
+[Bb]in/
+[Oo]bj/
+[Oo]ut/
+[Ll]og/
+[Ll]ogs/
+
+# Visual Studio 2015/2017 cache/options directory
+.vs/
+# Uncomment if you have tasks that create the project's static files in wwwroot
+#wwwroot/
+
+# Visual Studio 2017 auto generated files
+Generated\ Files/
+
+# MSTest test Results
+[Tt]est[Rr]esult*/
+[Bb]uild[Ll]og.*
+
+# NUnit
+*.VisualState.xml
+TestResult.xml
+nunit-*.xml
+
+# Build Results of an ATL Project
+[Dd]ebugPS/
+[Rr]eleasePS/
+dlldata.c
+
+# Benchmark Results
+BenchmarkDotNet.Artifacts/
+
+# .NET Core
+project.lock.json
+project.fragment.lock.json
+artifacts/
+
+# ASP.NET Scaffolding
+ScaffoldingReadMe.txt
+
+# StyleCop
+StyleCopReport.xml
+
+# Files built by Visual Studio
+*_i.c
+*_p.c
+*_h.h
+*.ilk
+*.meta
+*.obj
+*.iobj
+*.pch
+*.pdb
+*.ipdb
+*.pgc
+*.pgd
+*.rsp
+*.sbr
+*.tlb
+*.tli
+*.tlh
+*.tmp
+*.tmp_proj
+*_wpftmp.csproj
+*.log
+*.vspscc
+*.vssscc
+.builds
+*.pidb
+*.svclog
+*.scc
+
+# Chutzpah Test files
+_Chutzpah*
+
+# Visual C++ cache files
+ipch/
+*.aps
+*.ncb
+*.opendb
+*.opensdf
+*.sdf
+*.cachefile
+*.VC.db
+*.VC.VC.opendb
+
+# Visual Studio profiler
+*.psess
+*.vsp
+*.vspx
+*.sap
+
+# Visual Studio Trace Files
+*.e2e
+
+# TFS 2012 Local Workspace
+$tf/
+
+# Guidance Automation Toolkit
+*.gpState
+
+# ReSharper is a .NET coding add-in
+_ReSharper*/
+*.[Rr]e[Ss]harper
+*.DotSettings.user
+
+# TeamCity is a build add-in
+_TeamCity*
+
+# DotCover is a Code Coverage Tool
+*.dotCover
+
+# AxoCover is a Code Coverage Tool
+.axoCover/*
+!.axoCover/settings.json
+
+# Coverlet is a free, cross platform Code Coverage Tool
+coverage*.json
+coverage*.xml
+coverage*.info
+
+# Visual Studio code coverage results
+*.coverage
+*.coveragexml
+
+# NCrunch
+_NCrunch_*
+.*crunch*.local.xml
+nCrunchTemp_*
+
+# MightyMoose
+*.mm.*
+AutoTest.Net/
+
+# Web workbench (sass)
+.sass-cache/
+
+# Installshield output folder
+[Ee]xpress/
+
+# DocProject is a documentation generator add-in
+DocProject/buildhelp/
+DocProject/Help/*.HxT
+DocProject/Help/*.HxC
+DocProject/Help/*.hhc
+DocProject/Help/*.hhk
+DocProject/Help/*.hhp
+DocProject/Help/Html2
+DocProject/Help/html
+
+# Click-Once directory
+publish/
+
+# Publish Web Output
+*.[Pp]ublish.xml
+*.azurePubxml
+# Note: Comment the next line if you want to checkin your web deploy settings,
+# but database connection strings (with potential passwords) will be unencrypted
+*.pubxml
+*.publishproj
+
+# Microsoft Azure Web App publish settings. Comment the next line if you want to
+# checkin your Azure Web App publish settings, but sensitive information contained
+# in these scripts will be unencrypted
+PublishScripts/
+
+# NuGet Packages
+*.nupkg
+# NuGet Symbol Packages
+*.snupkg
+# The packages folder can be ignored because of Package Restore
+**/[Pp]ackages/*
+# except build/, which is used as an MSBuild target.
+!**/[Pp]ackages/build/
+# Uncomment if necessary however generally it will be regenerated when needed
+#!**/[Pp]ackages/repositories.config
+# NuGet v3's project.json files produces more ignorable files
+*.nuget.props
+*.nuget.targets
+
+# Microsoft Azure Build Output
+csx/
+*.build.csdef
+
+# Microsoft Azure Emulator
+ecf/
+rcf/
+
+# Windows Store app package directories and files
+AppPackages/
+BundleArtifacts/
+Package.StoreAssociation.xml
+_pkginfo.txt
+*.appx
+*.appxbundle
+*.appxupload
+
+# Visual Studio cache files
+# files ending in .cache can be ignored
+*.[Cc]ache
+# but keep track of directories ending in .cache
+!?*.[Cc]ache/
+
+# Others
+ClientBin/
+~$*
+*~
+*.dbmdl
+*.dbproj.schemaview
+*.jfm
+*.pfx
+*.publishsettings
+orleans.codegen.cs
+
+# Including strong name files can present a security risk
+# (https://github.com/github/gitignore/pull/2483#issue-259490424)
+#*.snk
+
+# Since there are multiple workflows, uncomment next line to ignore bower_components
+# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
+#bower_components/
+
+# RIA/Silverlight projects
+Generated_Code/
+
+# Backup & report files from converting an old project file
+# to a newer Visual Studio version. Backup files are not needed,
+# because we have git ;-)
+_UpgradeReport_Files/
+Backup*/
+UpgradeLog*.XML
+UpgradeLog*.htm
+ServiceFabricBackup/
+*.rptproj.bak
+
+# SQL Server files
+*.mdf
+*.ldf
+*.ndf
+
+# Business Intelligence projects
+*.rdl.data
+*.bim.layout
+*.bim_*.settings
+*.rptproj.rsuser
+*- [Bb]ackup.rdl
+*- [Bb]ackup ([0-9]).rdl
+*- [Bb]ackup ([0-9][0-9]).rdl
+
+# Microsoft Fakes
+FakesAssemblies/
+
+# GhostDoc plugin setting file
+*.GhostDoc.xml
+
+# Node.js Tools for Visual Studio
+.ntvs_analysis.dat
+node_modules/
+
+# Visual Studio 6 build log
+*.plg
+
+# Visual Studio 6 workspace options file
+*.opt
+
+# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
+*.vbw
+
+# Visual Studio LightSwitch build output
+**/*.HTMLClient/GeneratedArtifacts
+**/*.DesktopClient/GeneratedArtifacts
+**/*.DesktopClient/ModelManifest.xml
+**/*.Server/GeneratedArtifacts
+**/*.Server/ModelManifest.xml
+_Pvt_Extensions
+
+# Paket dependency manager
+.paket/paket.exe
+paket-files/
+
+# FAKE - F# Make
+.fake/
+
+# CodeRush personal settings
+.cr/personal
+
+# Python Tools for Visual Studio (PTVS)
+__pycache__/
+*.pyc
+
+# Cake - Uncomment if you are using it
+# tools/**
+# !tools/packages.config
+
+# Tabs Studio
+*.tss
+
+# Telerik's JustMock configuration file
+*.jmconfig
+
+# BizTalk build output
+*.btp.cs
+*.btm.cs
+*.odx.cs
+*.xsd.cs
+
+# OpenCover UI analysis results
+OpenCover/
+
+# Azure Stream Analytics local run output
+ASALocalRun/
+
+# MSBuild Binary and Structured Log
+*.binlog
+
+# NVidia Nsight GPU debugger configuration file
+*.nvuser
+
+# MFractors (Xamarin productivity tool) working folder
+.mfractor/
+
+# Local History for Visual Studio
+.localhistory/
+
+# BeatPulse healthcheck temp database
+healthchecksdb
+
+# Backup folder for Package Reference Convert tool in Visual Studio 2017
+MigrationBackup/
+
+# Ionide (cross platform F# VS Code tools) working folder
+.ionide/
+
+# Fody - auto-generated XML schema
+FodyWeavers.xsd

+ 25 - 0
AvaloniaApplicationBase.sln

@@ -0,0 +1,25 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.6.33829.357
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaApplicationBase", "AvaloniaApplicationBase\AvaloniaApplicationBase.csproj", "{24D1003F-2C91-4BE3-A873-4BB6D0C32C68}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Any CPU = Debug|Any CPU
+		Release|Any CPU = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{24D1003F-2C91-4BE3-A873-4BB6D0C32C68}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{24D1003F-2C91-4BE3-A873-4BB6D0C32C68}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{24D1003F-2C91-4BE3-A873-4BB6D0C32C68}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{24D1003F-2C91-4BE3-A873-4BB6D0C32C68}.Release|Any CPU.Build.0 = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+	GlobalSection(ExtensibilityGlobals) = postSolution
+		SolutionGuid = {9F091B6E-2CF0-4A55-B385-DF6E6D668425}
+	EndGlobalSection
+EndGlobal

+ 15 - 0
AvaloniaApplicationBase/App.axaml

@@ -0,0 +1,15 @@
+<Application xmlns="https://github.com/avaloniaui"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             x:Class="AvaloniaApplicationBase.App"
+             xmlns:local="using:AvaloniaApplicationBase"
+             RequestedThemeVariant="Default">
+             <!-- "Default" ThemeVariant follows system theme variant. "Dark" or "Light" are other available options. -->
+
+    <Application.DataTemplates>
+        <local:ViewLocator/>
+    </Application.DataTemplates>
+  
+    <Application.Styles>
+        <FluentTheme />
+    </Application.Styles>
+</Application>

+ 29 - 0
AvaloniaApplicationBase/App.axaml.cs

@@ -0,0 +1,29 @@
+using Avalonia;
+using Avalonia.Controls.ApplicationLifetimes;
+using Avalonia.Markup.Xaml;
+using AvaloniaApplicationBase.ViewModels;
+using AvaloniaApplicationBase.Views;
+
+namespace AvaloniaApplicationBase
+{
+    public partial class App : Application
+    {
+        public override void Initialize()
+        {
+            AvaloniaXamlLoader.Load(this);
+        }
+
+        public override void OnFrameworkInitializationCompleted()
+        {
+            if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
+            {
+                desktop.MainWindow = new MainWindow
+                {
+                    DataContext = new MainWindowViewModel(),
+                };
+            }
+
+            base.OnFrameworkInitializationCompleted();
+        }
+    }
+}

TEMPAT SAMPAH
AvaloniaApplicationBase/Assets/avalonia-logo.ico


+ 36 - 0
AvaloniaApplicationBase/AvaloniaApplicationBase.csproj

@@ -0,0 +1,36 @@
+<Project Sdk="Microsoft.NET.Sdk">
+  <PropertyGroup>
+    <OutputType>WinExe</OutputType>
+    <TargetFramework>net7.0</TargetFramework>
+    <Nullable>enable</Nullable>
+    <BuiltInComInteropSupport>true</BuiltInComInteropSupport>
+    <ApplicationManifest>app.manifest</ApplicationManifest>
+    <AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
+  </PropertyGroup>
+
+  <ItemGroup>
+    <AvaloniaResource Include="Assets\**" />
+  </ItemGroup>
+
+
+  <ItemGroup>
+    <PackageReference Include="Avalonia" Version="11.0.2" />
+    <PackageReference Include="Avalonia.Controls.ItemsRepeater" Version="11.0.2" />
+    <PackageReference Include="Avalonia.Desktop" Version="11.0.2" />
+    <PackageReference Include="Avalonia.Themes.Fluent" Version="11.0.2" />
+    <PackageReference Include="Avalonia.Fonts.Inter" Version="11.0.2" />
+    <!--Condition below is needed to remove Avalonia.Diagnostics package from build output in Release configuration.-->
+    <PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="11.0.2" />
+    <PackageReference Include="Avalonia.ReactiveUI" Version="11.0.2" />
+    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.14">
+      <PrivateAssets>all</PrivateAssets>
+      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+    </PackageReference>
+    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.11" />
+  </ItemGroup>
+
+
+  <ItemGroup>
+    <UpToDateCheckInput Remove="Views\AddCatPage.axaml" />
+  </ItemGroup>
+</Project>

+ 102 - 0
AvaloniaApplicationBase/Models/CatBaseContext.cs

@@ -0,0 +1,102 @@
+using System;
+using System.Collections.Generic;
+using Microsoft.EntityFrameworkCore;
+
+namespace AvaloniaApplicationBase.Models;
+
+public partial class CatBaseContext : DbContext
+{
+    public CatBaseContext()
+    {
+    }
+
+    public CatBaseContext(DbContextOptions<CatBaseContext> options)
+        : base(options)
+    {
+    }
+
+    public virtual DbSet<CatTable> CatTables { get; set; }
+
+    public virtual DbSet<GenderTable> GenderTables { get; set; }
+
+    public virtual DbSet<TraitCatTable> TraitCatTables { get; set; }
+
+    public virtual DbSet<TraitTable> TraitTables { get; set; }
+
+    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
+#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
+        => optionsBuilder.UseNpgsql("Host=edu.pg.ngknn.local;Port=5432;Database=CatBase;Username=43P;Password=444444");
+
+    protected override void OnModelCreating(ModelBuilder modelBuilder)
+    {
+        modelBuilder.Entity<CatTable>(entity =>
+        {
+            entity.HasKey(e => e.Id).HasName("cat_table_pk");
+
+            entity.ToTable("cat_table");
+
+            entity.Property(e => e.Id).HasColumnName("id");
+            entity.Property(e => e.Date)
+                .HasColumnType("timestamp without time zone")
+                .HasColumnName("date");
+            entity.Property(e => e.Gender).HasColumnName("gender");
+            entity.Property(e => e.Name)
+                .HasColumnType("character varying")
+                .HasColumnName("name");
+
+            entity.HasOne(d => d.GenderNavigation).WithMany(p => p.CatTables)
+                .HasForeignKey(d => d.Gender)
+                .OnDelete(DeleteBehavior.ClientSetNull)
+                .HasConstraintName("cat_table_fk");
+        });
+
+        modelBuilder.Entity<GenderTable>(entity =>
+        {
+            entity.HasKey(e => e.Id).HasName("gender_table_pk");
+
+            entity.ToTable("gender_table");
+
+            entity.Property(e => e.Id).HasColumnName("id");
+            entity.Property(e => e.Gender)
+                .HasColumnType("character varying")
+                .HasColumnName("gender");
+        });
+
+        modelBuilder.Entity<TraitCatTable>(entity =>
+        {
+            entity.HasKey(e => e.Id).HasName("trait_cat_table_pk");
+
+            entity.ToTable("trait_cat_table");
+
+            entity.Property(e => e.Id).HasColumnName("id");
+            entity.Property(e => e.IdCat).HasColumnName("id_cat");
+            entity.Property(e => e.IdTrait).HasColumnName("id_trait");
+
+            entity.HasOne(d => d.IdCatNavigation).WithMany(p => p.TraitCatTables)
+                .HasForeignKey(d => d.IdCat)
+                .OnDelete(DeleteBehavior.ClientSetNull)
+                .HasConstraintName("trait_cat_table_fk");
+
+            entity.HasOne(d => d.IdTraitNavigation).WithMany(p => p.TraitCatTables)
+                .HasForeignKey(d => d.IdTrait)
+                .OnDelete(DeleteBehavior.ClientSetNull)
+                .HasConstraintName("trait_cat_table_fk_1");
+        });
+
+        modelBuilder.Entity<TraitTable>(entity =>
+        {
+            entity.HasKey(e => e.Id).HasName("trait_table_pk");
+
+            entity.ToTable("trait_table");
+
+            entity.Property(e => e.Id).HasColumnName("id");
+            entity.Property(e => e.Trait)
+                .HasColumnType("character varying")
+                .HasColumnName("trait");
+        });
+
+        OnModelCreatingPartial(modelBuilder);
+    }
+
+    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
+}

+ 19 - 0
AvaloniaApplicationBase/Models/CatTable.cs

@@ -0,0 +1,19 @@
+using System;
+using System.Collections.Generic;
+
+namespace AvaloniaApplicationBase.Models;
+
+public partial class CatTable
+{
+    public int Id { get; set; }
+
+    public string Name { get; set; } = null!;
+
+    public DateTime Date { get; set; }
+
+    public int Gender { get; set; }
+
+    public virtual GenderTable GenderNavigation { get; set; } = null!;
+
+    public virtual ICollection<TraitCatTable> TraitCatTables { get; set; } = new List<TraitCatTable>();
+}

+ 13 - 0
AvaloniaApplicationBase/Models/GenderTable.cs

@@ -0,0 +1,13 @@
+using System;
+using System.Collections.Generic;
+
+namespace AvaloniaApplicationBase.Models;
+
+public partial class GenderTable
+{
+    public int Id { get; set; }
+
+    public string Gender { get; set; } = null!;
+
+    public virtual ICollection<CatTable> CatTables { get; set; } = new List<CatTable>();
+}

+ 27 - 0
AvaloniaApplicationBase/Models/PartialCat.cs

@@ -0,0 +1,27 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace AvaloniaApplicationBase.Models
+{
+    public partial class CatTable
+    {
+        public string Traits // свойство, возвращающее список черт характера кота
+        {
+            get
+            {
+                
+                string s = (TraitCatTables.Count == 0) ? "Черт нет  " : (TraitCatTables.Count == 1) ? "Черта кота: " : "Черты кота: ";
+
+                // цикл, который проходит по таблице TraitCatTables (с помощью свойства IdTraitNavigation, которое связывает данную таблицу с CatTable)
+                foreach (var item in TraitCatTables)
+                {
+                    s += item.IdTraitNavigation.Trait+", "; // добавление черты кота в строку
+                }
+                return s[0..(s.Length - 2)];
+            }
+        }
+    }
+}

+ 17 - 0
AvaloniaApplicationBase/Models/TraitCatTable.cs

@@ -0,0 +1,17 @@
+using System;
+using System.Collections.Generic;
+
+namespace AvaloniaApplicationBase.Models;
+
+public partial class TraitCatTable
+{
+    public int Id { get; set; }
+
+    public int IdCat { get; set; }
+
+    public int IdTrait { get; set; }
+
+    public virtual CatTable IdCatNavigation { get; set; } = null!;
+
+    public virtual TraitTable IdTraitNavigation { get; set; } = null!;
+}

+ 13 - 0
AvaloniaApplicationBase/Models/TraitTable.cs

@@ -0,0 +1,13 @@
+using System;
+using System.Collections.Generic;
+
+namespace AvaloniaApplicationBase.Models;
+
+public partial class TraitTable
+{
+    public int Id { get; set; }
+
+    public string Trait { get; set; } = null!;
+
+    public virtual ICollection<TraitCatTable> TraitCatTables { get; set; } = new List<TraitCatTable>();
+}

+ 24 - 0
AvaloniaApplicationBase/Program.cs

@@ -0,0 +1,24 @@
+using Avalonia;
+using Avalonia.ReactiveUI;
+using System;
+
+namespace AvaloniaApplicationBase
+{
+    internal class Program
+    {
+        // Initialization code. Don't use any Avalonia, third-party APIs or any
+        // SynchronizationContext-reliant code before AppMain is called: things aren't initialized
+        // yet and stuff might break.
+        [STAThread]
+        public static void Main(string[] args) => BuildAvaloniaApp()
+            .StartWithClassicDesktopLifetime(args);
+
+        // Avalonia configuration, don't remove; also used by visual designer.
+        public static AppBuilder BuildAvaloniaApp()
+            => AppBuilder.Configure<App>()
+                .UsePlatformDetect()
+                .WithInterFont()
+                .LogToTrace()
+                .UseReactiveUI();
+    }
+}

+ 28 - 0
AvaloniaApplicationBase/ViewLocator.cs

@@ -0,0 +1,28 @@
+using Avalonia.Controls;
+using Avalonia.Controls.Templates;
+using AvaloniaApplicationBase.ViewModels;
+using System;
+
+namespace AvaloniaApplicationBase
+{
+    public class ViewLocator : IDataTemplate
+    {
+        public Control Build(object data)
+        {
+            var name = data.GetType().FullName!.Replace("ViewModel", "View");
+            var type = Type.GetType(name);
+
+            if (type != null)
+            {
+                return (Control)Activator.CreateInstance(type)!;
+            }
+
+            return new TextBlock { Text = "Not Found: " + name };
+        }
+
+        public bool Match(object data)
+        {
+            return data is ViewModelBase;
+        }
+    }
+}

+ 65 - 0
AvaloniaApplicationBase/ViewModels/AddCatPageViewModel.cs

@@ -0,0 +1,65 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using AvaloniaApplicationBase.Models;
+using ReactiveUI;
+
+namespace AvaloniaApplicationBase.ViewModels
+{
+    public class AddCatPageViewModel : ReactiveObject
+    {
+        string name = "";
+        DateTime date = DateTime.Now;
+        int gender = -1;
+        List<string> selectedTraitsCat = new List<string>();
+
+
+        public string Name { get => name; set => name = value; }
+        public string Date { get => date.ToString(); set => date = DateTime.Parse(value); }
+        public int Gender { get => gender; set => gender = value; }
+        public List<string> AllTraits => MainWindowViewModel.myConnection.TraitTables.Select(x => x.Trait).ToList();
+
+        public List<string> SelectedTraitsCat 
+        { 
+            get => selectedTraitsCat; 
+            set => this.RaiseAndSetIfChanged(ref selectedTraitsCat,value); 
+        }
+
+        public string SelectedTrait
+        {
+            get => null;
+            set
+            {
+                selectedTraitsCat.Add(value);
+                SelectedTraitsCat = new List<string>(selectedTraitsCat);
+            }
+        }
+        public void AddNewCat()
+        {
+            CatTable newCat = new CatTable()
+            {
+                Name = name,
+                Date = date,
+                Gender = gender + 1,
+            };
+            MainWindowViewModel.myConnection.Add(newCat);
+            MainWindowViewModel.myConnection.SaveChanges();
+
+            foreach (string item in selectedTraitsCat)
+            {
+                TraitTable tt = MainWindowViewModel.myConnection.TraitTables.FirstOrDefault(x => x.Trait == item);
+                if (tt!=null)
+                {
+                TraitCatTable TCT = new TraitCatTable()
+                {
+                    IdCat = newCat.Id,
+                    IdTrait = tt.Id
+                };
+                MainWindowViewModel.myConnection.TraitCatTables.Add(TCT);
+                }
+                
+            }
+            MainWindowViewModel.myConnection.SaveChanges();
+        }
+    }
+}

+ 49 - 0
AvaloniaApplicationBase/ViewModels/MainWindowViewModel.cs

@@ -0,0 +1,49 @@
+using Avalonia.Controls;
+using AvaloniaApplicationBase.Models;
+using AvaloniaApplicationBase.Views;
+using Microsoft.EntityFrameworkCore;
+using ReactiveUI;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace AvaloniaApplicationBase.ViewModels
+{
+    public class MainWindowViewModel : ViewModelBase
+    {
+        public static CatBaseContext myConnection = new CatBaseContext(); // для подключения БД
+
+        UserControl us = new ShowCatsPage(); // сюда помещаются страницы (по умолчанию будет показана страница с просмотром информации)
+        
+        // свойство для изменения страниц
+        public UserControl US 
+        { 
+            get => us; 
+            set => this.RaiseAndSetIfChanged(ref us, value); 
+        }
+
+        ShowCatsPageViewModel showCatsVM = new ShowCatsPageViewModel(); // объект VM с кодом для просмотром информации о котах
+        
+        // свойсво для изменения выше созданной переменной
+        public ShowCatsPageViewModel ShowCatsVM 
+        { 
+            get => showCatsVM; 
+            set => showCatsVM = value; 
+        }
+        public AddCatPageViewModel AddCat { get => addCat; set => addCat = value; }
+
+        AddCatPageViewModel addCat = new AddCatPageViewModel();
+
+        public void ShowAddCatPage()
+        {
+            US = new AddCatPage();
+        }
+
+        public void deleteCat(int IdCat) // для удаления объекта из шаблона
+        {
+            CatTable catDelete = myConnection.CatTables.First(x=>x.Id == IdCat); // находим удаляемого кота в базе данных
+            myConnection.CatTables.Remove(catDelete); // удаляем кота
+            myConnection.SaveChanges(); // сохраняем изменения
+            US = new ShowCatsPage(); // обновляем страницу для отображения актуального списка
+        }
+    }
+}

+ 16 - 0
AvaloniaApplicationBase/ViewModels/ShowCatsPageViewModel.cs

@@ -0,0 +1,16 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using AvaloniaApplicationBase.Models;
+using Microsoft.EntityFrameworkCore;
+using ReactiveUI;
+
+namespace AvaloniaApplicationBase.ViewModels
+{
+	public class ShowCatsPageViewModel : ReactiveObject
+	{
+        // Include - äëÿ òàáëèö, íåïîñðåäñòâåííî ñâÿçàííûõ ñâÿçàííûõ äðóã ñ äðóãîì
+        // ThenInclude - äëÿ ïîñëåäîâàòëåüíîãî ñîåäèíåíèÿ òàáëèö, èçíà÷àëüíî äðóã ñ äðóãîì íå ñâÿçàííûìè (ïîäðîáíåå â ôàéëå â moodle)
+        public List<CatTable> CT => MainWindowViewModel.myConnection.CatTables.Include(x => x.GenderNavigation).Include(x => x.TraitCatTables).ThenInclude(x => x.IdTraitNavigation).ToList();
+    }
+}

+ 8 - 0
AvaloniaApplicationBase/ViewModels/ViewModelBase.cs

@@ -0,0 +1,8 @@
+using ReactiveUI;
+
+namespace AvaloniaApplicationBase.ViewModels
+{
+    public class ViewModelBase : ReactiveObject
+    {
+    }
+}

+ 26 - 0
AvaloniaApplicationBase/Views/AddCatPage.axaml

@@ -0,0 +1,26 @@
+<UserControl xmlns="https://github.com/avaloniaui"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+			 xmlns:vm="using:AvaloniaApplicationBase.ViewModels"
+             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+			 x:DataType="vm:MainWindowViewModel"
+             mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
+             x:Class="AvaloniaApplicationBase.Views.AddCatPage">
+	<Grid>
+		<StackPanel>
+			<TextBlock>Введите имя</TextBlock>
+			<TextBox Text="{Binding AddCat.Name}"></TextBox>
+			<TextBlock>Выберите дату</TextBlock>
+			<DatePicker SelectedDate="{Binding AddCat.Date}"></DatePicker>
+			<TextBlock>Выберите пол</TextBlock>
+			<ComboBox SelectedIndex="{Binding AddCat.Gender}">
+				<ComboBoxItem>Мужской</ComboBoxItem>
+				<ComboBoxItem>Женский</ComboBoxItem>
+			</ComboBox>
+			<ListBox ItemsSource="{Binding AddCat.SelectedTraitsCat}"></ListBox>
+			<TextBlock>Выберите черты характера</TextBlock>
+			<ComboBox ItemsSource="{Binding AddCat.AllTraits}" SelectedValue="{Binding AddCat.SelectedTrait}"></ComboBox>
+			<Button Command="{Binding AddCat.AddNewCat}">Добавить кота</Button>
+		</StackPanel>
+	</Grid>
+</UserControl>

+ 13 - 0
AvaloniaApplicationBase/Views/AddCatPage.axaml.cs

@@ -0,0 +1,13 @@
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Markup.Xaml;
+
+namespace AvaloniaApplicationBase.Views;
+
+public partial class AddCatPage : UserControl
+{
+    public AddCatPage()
+    {
+        InitializeComponent();
+    }
+}

+ 30 - 0
AvaloniaApplicationBase/Views/MainWindow.axaml

@@ -0,0 +1,30 @@
+<Window xmlns="https://github.com/avaloniaui"
+        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+        xmlns:vm="using:AvaloniaApplicationBase.ViewModels"
+        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+        mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
+        x:Class="AvaloniaApplicationBase.Views.MainWindow"
+        x:DataType="vm:MainWindowViewModel"
+        Icon="/Assets/avalonia-logo.ico"
+        Title="AvaloniaApplicationBase">
+	<Window.Styles>
+		<Style Selector="TextBlock">
+			<Setter Property="FontSize" Value="28"></Setter>
+		</Style>
+		<Style Selector="Button">
+			<Setter Property="Background" Value="Violet"/>
+			<Setter Property="FontSize" Value="28"/>
+			<Setter Property="FontWeight" Value="Bold"/>
+		</Style>
+	</Window.Styles>
+    <Design.DataContext>
+        <!-- This only sets the DataContext for the previewer in an IDE,
+             to set the actual DataContext for runtime, set the DataContext property in code (look at App.axaml.cs) -->
+        <vm:MainWindowViewModel/>
+    </Design.DataContext>
+	<Grid>
+		<ContentControl Content="{Binding US}"></ContentControl>
+	</Grid>
+	
+</Window>

+ 12 - 0
AvaloniaApplicationBase/Views/MainWindow.axaml.cs

@@ -0,0 +1,12 @@
+using Avalonia.Controls;
+
+namespace AvaloniaApplicationBase.Views
+{
+    public partial class MainWindow : Window
+    {
+        public MainWindow()
+        {
+            InitializeComponent();
+        }
+    }
+}

+ 30 - 0
AvaloniaApplicationBase/Views/ShowCatsPage.axaml

@@ -0,0 +1,30 @@
+
+<UserControl xmlns="https://github.com/avaloniaui"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+			 xmlns:vm="using:AvaloniaApplicationBase.ViewModels"
+             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+			 x:DataType="vm:MainWindowViewModel"
+             mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
+             x:Class="AvaloniaApplicationBase.Views.ShowCatsPage">
+	
+	<Grid RowDefinitions="*,9*">
+		<Button Grid.Row="0" Command="{Binding ShowAddCatPage}">Добавить кота</Button>
+		<ListBox ItemsSource="{Binding ShowCatsVM.CT}" Grid.Row="1">
+			<ListBox.ItemTemplate>
+				<DataTemplate>
+					<Border CornerRadius="5" BorderBrush="Violet" BorderThickness="2" Padding="15">
+							<StackPanel>
+								<TextBlock Text="{Binding Name}"></TextBlock>
+								<TextBlock Text="{Binding Date}"></TextBlock>
+								<TextBlock Text="{Binding GenderNavigation.Gender}"></TextBlock>
+								<TextBlock Text="{Binding Traits}"></TextBlock>
+								<!--Команда для привязки метода с удалением к методу в шаблоне-->
+								<Button Content="Удалить" Command="{Binding $parent[Window].((vm:MainWindowViewModel)DataContext).deleteCat}" CommandParameter="{Binding Id}"></Button>
+							</StackPanel>
+					</Border>
+				</DataTemplate>
+			</ListBox.ItemTemplate>
+		</ListBox>
+	</Grid>
+</UserControl>

+ 13 - 0
AvaloniaApplicationBase/Views/ShowCatsPage.axaml.cs

@@ -0,0 +1,13 @@
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Markup.Xaml;
+
+namespace AvaloniaApplicationBase.Views;
+
+public partial class ShowCatsPage : UserControl
+{
+    public ShowCatsPage()
+    {
+        InitializeComponent();
+    }
+}

+ 18 - 0
AvaloniaApplicationBase/app.manifest

@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8"?>
+<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
+  <!-- This manifest is used on Windows only.
+       Don't remove it as it might cause problems with window transparency and embeded controls.
+       For more details visit https://learn.microsoft.com/en-us/windows/win32/sbscs/application-manifests -->
+  <assemblyIdentity version="1.0.0.0" name="AvaloniaApplicationBase.Desktop"/>
+
+  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
+    <application>
+      <!-- A list of the Windows versions that this application has been tested on
+           and is designed to work with. Uncomment the appropriate elements
+           and Windows will automatically select the most compatible environment. -->
+
+      <!-- Windows 10 -->
+      <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
+    </application>
+  </compatibility>
+</assembly>