WPF+SQLite+MVVM Demo

一.包:

  • CommunityToolkit.Mvvm
  • System.Data.SQLite.Core
  • Microsoft.Extensions.Hosting

二:App.xaml

<Application x:Class="SqliteDemo.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:SqliteDemo"> <!--StartupUri="MainWindow.xaml"--> <Application.Resources> </Application.Resources> </Application>

三.App.xaml.cs

using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using SqliteDemo.ViewModels; using System.Configuration; using System.Data; using System.Windows; namespace SqliteDemo { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { private readonly IHost _host; public App() { _host = Host.CreateDefaultBuilder() .ConfigureServices((context, services) => { services.AddSingleton<MainWindowViewModel>(); }) .Build(); } protected override async void OnStartup(StartupEventArgs e) { await _host.StartAsync(); var mainWindow = new MainWindow { DataContext = _host.Services.GetRequiredService<MainWindowViewModel>() }; mainWindow.Show(); base.OnStartup(e); } protected override async void OnExit(ExitEventArgs e) { await _host.StopAsync(); base.OnExit(e); } } }

四.MainWindow.xaml

<Window x:Class="SqliteDemo.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:SqliteDemo" xmlns:converters="clr-namespace:SqliteDemo.Converters" mc:Ignorable="d" Title="WPF SQLite Demo" Height="450" Width="800"> <Window.Resources> <converters:StringToVisibilityConverter x:Key="StringToVisibilityConverter"/> </Window.Resources> <Grid Margin="10"> <StackPanel> <Grid Height="26" Margin="0,0,0,5"> <TextBox Text="{Binding NewUserName, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" /> <TextBlock Text="输入名称" Foreground="Gray" IsHitTestVisible="False" Margin="5,0,0,0" VerticalAlignment="Center" Visibility="{Binding NewUserName, Converter={StaticResource StringToVisibilityConverter}}" /> </Grid> <!-- Age Input --> <Grid Height="26" Margin="0,0,0,10"> <TextBox Text="{Binding NewUserAgeText, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" /> <TextBlock Text="输入年龄" Foreground="Gray" IsHitTestVisible="False" Margin="5,0,0,0" VerticalAlignment="Center" Visibility="{Binding NewUserAgeText, Converter={StaticResource StringToVisibilityConverter}}" /> </Grid> <Button Content="Add User" Command="{Binding AddUserCommand}" Margin="0,0,0,10"/> <ListView ItemsSource="{Binding Users}"> <ListView.View> <GridView> <GridViewColumn Header="ID" DisplayMemberBinding="{Binding Id}" Width="50"/> <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="200"/> <GridViewColumn Header="Age" DisplayMemberBinding="{Binding Age}" Width="50"/> </GridView> </ListView.View> </ListView> </StackPanel> </Grid> </Window>

五.MainWindow.xaml.cs

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; namespace SqliteDemo { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } }

六.MainWindowViewModel.cs

using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using SqliteDemo.Database; using SqliteDemo.Models; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SqliteDemo.ViewModels { public partial class MainWindowViewModel : ObservableObject { private readonly DbContext _dbContext; [ObservableProperty] private ObservableCollection<User> _users; [ObservableProperty] private string _newUserName = ""; [ObservableProperty] private string _newUserAgeText = ""; public MainWindowViewModel() { _dbContext = new DbContext("Users.db"); LoadUsers(); } [RelayCommand] private void AddUser() { if (string.IsNullOrWhiteSpace(NewUserName) || string.IsNullOrWhiteSpace(NewUserAgeText)) return; if (!int.TryParse(NewUserAgeText, out int age)) return; using var connection = _dbContext.GetConnection(); connection.Open(); var command = connection.CreateCommand(); command.CommandText = "INSERT INTO Users (Name, Age) VALUES (@name, @age)"; command.Parameters.AddWithValue("@name", NewUserName); command.Parameters.AddWithValue("@age", age); command.ExecuteNonQuery(); LoadUsers(); // 清空输入 NewUserName = ""; NewUserAgeText = ""; } private void LoadUsers() { using var connection = _dbContext.GetConnection(); connection.Open(); var command = connection.CreateCommand(); command.CommandText = "SELECT * FROM Users"; using var reader = command.ExecuteReader(); var users = new ObservableCollection<User>(); while (reader.Read()) { users.Add(new User { Id = reader.GetInt32(0), Name = reader.GetString(1), Age = reader.GetInt32(2) }); } Users = users; } } }

七、Models.User

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SqliteDemo.Models { public class User { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } }

八.Database.DbContext

using System; using System.Collections.Generic; using System.Data.SQLite; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SqliteDemo.Database { public class DbContext { private readonly string _connectionString; public DbContext(string dbPath) { _connectionString = $"Data Source={dbPath};Version=3;"; InitializeDatabase(); } private void InitializeDatabase() { using var connection = new SQLiteConnection(_connectionString); connection.Open(); var command = connection.CreateCommand(); command.CommandText = @"CREATE TABLE IF NOT EXISTS Users ( Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT NOT NULL, Age INTEGER NOT NULL );"; command.ExecuteNonQuery(); } public SQLiteConnection GetConnection() => new SQLiteConnection(_connectionString); } }

九.Converters.StringToVisibilityConverter

using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; namespace SqliteDemo.Converters { public class StringToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return string.IsNullOrWhiteSpace(value as string) ? Visibility.Visible : Visibility.Hidden; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/1168706.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

一篇就够了!网络安全终极清单:定义、核心技术与防范策略全解析(附学习资源)

伴随着互联网的发展&#xff0c;它已经成为我们生活中不可或缺的存在&#xff0c;无论是个人还是企业&#xff0c;都离不开互联网。正因为互联网得到了重视&#xff0c;网络安全问题也随之加剧&#xff0c;给我们的信息安全造成严重威胁&#xff0c;而想要有效规避这些风险&…

网络安全从入门到精通通关指南:核心概念、技术框架与主动防御策略详解

伴随着互联网的发展&#xff0c;它已经成为我们生活中不可或缺的存在&#xff0c;无论是个人还是企业&#xff0c;都离不开互联网。正因为互联网得到了重视&#xff0c;网络安全问题也随之加剧&#xff0c;给我们的信息安全造成严重威胁&#xff0c;而想要有效规避这些风险&…

网络安全实战速通核心要点:技术盘点、最佳实践与避坑指南总结

1.网络安全的概念 网络安全的定义 ISO对网络安全的定义&#xff1a;网络系统的软件、硬件以及系统中存储和传输的数据受到保护&#xff0c;不因偶然的或者恶意的原因而遭到破坏、更改、泄露&#xff0c;网络系统连续可靠正常地运行&#xff0c;网络服务不中断。 网络安全的属…

网络安全核心技术栈硬核归档:一份工程师的进阶路线与策略反思

1.网络安全的概念 网络安全的定义 ISO对网络安全的定义&#xff1a;网络系统的软件、硬件以及系统中存储和传输的数据受到保护&#xff0c;不因偶然的或者恶意的原因而遭到破坏、更改、泄露&#xff0c;网络系统连续可靠正常地运行&#xff0c;网络服务不中断。 网络安全的属…

基于python的开放自习室座位预约管理系统设计与实现

基于Python的开放自习室座位预约管理系统设计与实现 第一章 系统整体架构设计 基于Python的开放自习室座位预约管理系统以“高效利用资源、便捷用户预约”为核心目标&#xff0c;采用“前端-后端-数据层”三层架构。系统核心包含五大功能模块&#xff1a;用户管理模块、座位管理…

信息系统是指由人、技术、数据和流程构成的集成化体系,旨在采集、存储、处理、传输和提供信息

一、核心内容梳理&#xff08;更新版报告&#xff09; 信息系统与信息系统工程概述 信息系统是指由人、技术、数据和流程构成的集成化体系&#xff0c;旨在采集、存储、处理、传输和提供信息&#xff0c;以支持组织的管理决策与业务运作。典型的信息系统包括事务处理系统&#…

全面解析iOS应用代码混淆和加密加固方法与实践注意事项

android 代码混淆注意点 ios代码混淆技术 为了给iOS app加固&#xff0c;我们可以采取以下几种方式&#xff1a; 1.代码混淆 代码混淆是通过修改源代码结构和变量名&#xff0c;使得代码难以被理解和反编译。这可以防止黑客获取应用程序的代码&#xff0c;因为即使他们能够获得…

Cloudera CDP/CMP华为鲲鹏版下 Spark应用加速,华为昇腾芯片的实用配置过程

要将 Apache Spark 应用与华为昇腾&#xff08;Ascend&#xff09;芯片集成以实现 AI/ML 环节加速&#xff0c;需构建一个“Spark 负责数据预处理 昇腾负责模型训练/推理”的混合架构。以下是截至 2026 年的完整、可落地的实用配置流程&#xff0c;适用于企业级部署&#xff0…

基于大数据的热门旅游景点推荐系统设计与实现

第一章 系统开发背景与意义 随着文旅产业复苏与大众出行需求激增&#xff0c;旅游决策面临信息过载困境&#xff1a;全网旅游信息碎片化&#xff08;攻略、评价、实时动态等&#xff09;&#xff0c;用户筛选有效内容耗时耗力&#xff1b;传统推荐依赖人工编辑或单一热度排名&a…

基于SpringBoot与微信小程序的图书馆座位预约系统设计与实现

一、系统开发背景与意义 在高校图书馆或公共图书馆中&#xff0c;座位资源紧张与管理效率低下的矛盾日益凸显。传统人工占座、纸质登记等方式&#xff0c;不仅浪费人力成本&#xff0c;还易引发读者间的座位纠纷&#xff0c;导致座位资源利用率低。随着移动互联网技术的普及&am…

输入某餐厅的菜品名称,价格,销量,计算单品利润,(成本为价格的40%),输出利润最高的菜品。

为你完整设计一个餐厅菜品利润分析系统&#xff0c;结合大数据与智能管理课程的思想&#xff0c;从场景到代码、从模块到文档&#xff0c;全部覆盖。1. 实际应用场景 & 痛点引入场景你是某餐厅的管理者或数据分析师&#xff0c;手头有菜品销售数据&#xff08;菜品名称、售…

基于Python的大数据化妆品销售系统设计与实现

一、系统开发背景与核心目标 当前化妆品销售市场存在“供需匹配低效、数据价值未充分挖掘”的问题&#xff1a;品牌方难以通过分散的销售数据洞察用户需求&#xff0c;导致产品库存积压或热门单品断货&#xff1b;线下门店缺乏对顾客消费偏好的精准分析&#xff0c;营销活动针对…

XZ后门事件深度解析:漏洞机理、攻击演示与防御策略

XZ 后门 (CVE-2024–3094)&#xff1a;事件分析、工具后门解析与防御措施 目录&#xff1a; 引言漏洞详情风险评估与缓解措施CVE-2024–3094 调查结论 1- 引言&#xff1a; 一位微软开发人员于周五发布了一项重大发现&#xff0c;震动了科技界&#xff1a;在几乎所有 Linux 和类…

信息化项目总结报告(文件WORD)

1. 项目概要 1.1. 项目基本信息 1.2. 项目期间 1.3. 项目成果 1.4. 开发工具和环境 2. 项目工作分析 2.1. 项目需求变更 2.2. 项目计划与进度实施 2.3. 项目总投入情况 2.4. 项目总收益情况 2.5. 项目质量情况 2.6. 风险管理实施情况 3. 经验与教训 …

2026必看:10个高品质艺术油画素材网站,免费商用选哪个?

对于设计师、自媒体创作者或艺术爱好者来说&#xff0c;找到**高品质艺术油画素材**往往像大海捞针——要么是模糊不清的低分辨率图&#xff0c;要么是版权受限无法商用。尤其是在2026年&#xff0c;内容创作的版权意识越来越强&#xff0c;免费且合法的素材资源更是稀缺。今天…

基于Python的个性化音乐推荐系统设计与实现

一、系统开发背景与核心目标 当前音乐平台虽坐拥海量曲库&#xff0c;但传统推荐模式存在明显局限&#xff1a;多依赖热门榜单或简单曲风分类&#xff0c;难以捕捉用户深层音乐偏好——例如喜欢某首民谣的用户&#xff0c;可能同时偏爱小众独立音乐人作品&#xff0c;却被平台推…

2026包装设计纹理素材推荐:10个网站提升设计质感!

包装设计里&#xff0c;纹理素材就像给产品加了一层“隐形滤镜”——能让消费者光看图片就感受到质感&#xff0c;瞬间拉近和品牌的距离。如果你正愁找不到合适的纹理素材&#xff0c;这篇文章绝对能帮到你&#xff01;下面为你整理了10个优质素材网站&#xff0c;每个都能找到…

SpringBoot+Vue 厨艺交流平台管理平台源码【适合毕设/课设/学习】Java+MySQL

&#x1f4a1;实话实说&#xff1a;CSDN上做毕设辅导的都是专业技术服务&#xff0c;大家都要生活&#xff0c;这个很正常。我和其他人不同的是&#xff0c;我有自己的项目库存&#xff0c;不需要找别人拿货再加价&#xff0c;所以能给到超低价格。摘要 随着互联网技术的快速发…

AI论文写作从零到一:9款神器实测手把手指南,一键生成真实文献综述

还在为毕业论文、课程论文、研究报告抓耳挠腮吗&#xff1f;从选题、找文献、搭框架到反复修改&#xff0c;每一步都充满挑战。别担心&#xff0c;AI时代&#xff0c;我们有强大的“神器”工具。本文将通过一篇手把手实操指南&#xff0c;为你深度测评9款顶尖AI论文工具&#x…

《异构计算图中通信与计算的协同决策逻辑指南》

异构计算图的划分本质是拓扑感知与资源适配的深度博弈,其核心矛盾并非简单的任务拆分,而是在节点算力差异、链路带宽波动、任务依赖复杂度交织的场景中,找到通信延迟梯度与计算效率峰值的动态平衡点。最初接触这类问题时,很容易陷入均匀划分的认知误区,认为将任务量平均分…