news 2026/4/17 23:12:49

WPF+SQLite+MVVM Demo

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
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(); } } }
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/17 21:51:59

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

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

作者头像 李华
网站建设 2026/4/9 23:38:04

低端游戏官网 - 支持网页在线玩经典DOS/Windows游戏平台

随着Web技术的快速发展&#xff0c;在浏览器中运行传统本地应用程序已成为现实。低端游戏&#xff08;RetroOnline&#xff09;网站利用先进的Web技术&#xff0c;成功实现了经典游戏的无缝迁移&#xff0c;让用户无需安装任何软件即可重温《红色警戒》、《暗黑破坏神》等经典作…

作者头像 李华
网站建设 2026/4/16 14:04:46

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

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

作者头像 李华
网站建设 2026/4/16 12:53:40

域名代购适合哪些人?并不是所有人都需要

在域名交易市场中&#xff0c;“域名代购”一直是一个常被提起、却容易被误解的服务。很多人以为代购只是“帮忙买域名”&#xff0c;但实际上&#xff0c;是否需要代购&#xff0c;取决于你想要什么样的域名&#xff0c;以及你愿意为成功率付出多少成本。一、想要特定域名&…

作者头像 李华
网站建设 2026/4/8 21:48:14

基于Python的高校毕业生招聘信息推荐系统设计与实现

一、系统开发背景与核心目标 高校毕业生在求职过程中常面临“信息过载与精准匹配缺失”的双重困境&#xff1a;招聘信息分散于各类平台&#xff0c;毕业生需耗费大量时间筛选有效内容&#xff1b;传统推荐多依赖简单关键词匹配&#xff0c;难以结合专业背景、技能特长、职业规划…

作者头像 李华