WPF Blazor Hybrid:如何在代码后置中使用Razor页面的值?
购物清单数据存入SQL数据库的实现方案
前提准备
先在SQL数据库(如SQL Server/SQLite)中创建存储购物项的表:
CREATE TABLE ShoppingItems ( Id INT PRIMARY KEY IDENTITY(1,1), -- SQLite替换为INTEGER PRIMARY KEY AUTOINCREMENT ItemName NVARCHAR(100) NOT NULL, Category NVARCHAR(50) NOT NULL );
方案一:Blazor组件代码后置直接处理数据库操作
1. 完善Index.razor的UI布局
将输入框和下拉菜单合并到同一个表单,添加提交按钮并完成双向绑定:
<form @onsubmit="HandleSubmit"> <input type="text" id="id_item1" name="item1" @bind="@inputValue1" placeholder="输入商品名称" required><br> <select name="categories" id="cat1" @bind="@selectedCategory" required> <option value="" disabled selected>选择类别</option> <option value="食品">食品</option> <option value="日用品">日用品</option> <option value="家电">家电</option> <!-- 按需添加更多类别选项 --> </select><br> <button type="submit">添加到清单</button> </form>
注:
@bind已自动处理值同步,无需额外的@oninput事件;添加required属性可触发前端表单验证。
2. 在Index.razor.cs实现数据插入逻辑
直接使用ADO.NET操作数据库,无需依赖MVVM框架:
using Microsoft.AspNetCore.Components; using System.Data.SqlClient; // SQLite替换为Microsoft.Data.Sqlite namespace YourProjectNamespace.Pages; public partial class Index : ComponentBase { private string inputValue1 = string.Empty; private string selectedCategory = string.Empty; // 数据库连接字符串,建议从appsettings.json读取,示例为SQL Server连接 private readonly string _connectionString = "Server=你的服务器地址;Database=你的数据库名;Trusted_Connection=True;TrustServerCertificate=True;"; // SQLite连接字符串:"Data Source=ShoppingList.db;" private async Task HandleSubmit() { // 跳过空值提交 if (string.IsNullOrWhiteSpace(inputValue1) || string.IsNullOrWhiteSpace(selectedCategory)) return; try { using var conn = new SqlConnection(_connectionString); // SQLite替换为SqliteConnection await conn.OpenAsync(); var insertSql = "INSERT INTO ShoppingItems (ItemName, Category) VALUES (@ItemName, @Category)"; using var cmd = new SqlCommand(insertSql, conn); // SQLite替换为SqliteCommand cmd.Parameters.AddWithValue("@ItemName", inputValue1); cmd.Parameters.AddWithValue("@Category", selectedCategory); await cmd.ExecuteNonQueryAsync(); // 提交后清空输入 inputValue1 = string.Empty; selectedCategory = string.Empty; } catch (Exception ex) { // 可添加错误提示逻辑,如显示错误文本 Console.WriteLine($"插入失败:{ex.Message}"); } } }
方案二:调用WPF MainWindow代码后置的数据库方法
如果希望将数据库逻辑放在WPF端执行,可通过依赖注入让Blazor组件调用MainWindow的方法:
1. 在MainWindow.xaml.cs实现数据库操作方法
using System.Data.SqlClient; // SQLite替换为Microsoft.Data.Sqlite using System.Windows; namespace YourProjectNamespace; public partial class MainWindow : Window { private readonly string _connectionString = "Server=你的服务器地址;Database=你的数据库名;Trusted_Connection=True;TrustServerCertificate=True;"; public MainWindow() { InitializeComponent(); // 将MainWindow实例注册到Blazor服务容器 var blazorWebView = this.FindName("blazorWebView") as BlazorWebView; blazorWebView?.Services.AddSingleton(this); } public async Task AddShoppingItem(string itemName, string category) { if (string.IsNullOrWhiteSpace(itemName) || string.IsNullOrWhiteSpace(category)) return; try { using var conn = new SqlConnection(_connectionString); await conn.OpenAsync(); var insertSql = "INSERT INTO ShoppingItems (ItemName, Category) VALUES (@ItemName, @Category)"; using var cmd = new SqlCommand(insertSql, conn); cmd.Parameters.AddWithValue("@ItemName", itemName); cmd.Parameters.AddWithValue("@Category", category); await cmd.ExecuteNonQueryAsync(); } catch (Exception ex) { MessageBox.Show($"添加失败:{ex.Message}", "错误"); } } }
2. 在Blazor组件中调用MainWindow方法
修改Index.razor.cs,注入MainWindow实例并调用其方法:
using Microsoft.AspNetCore.Components; using YourProjectNamespace; namespace YourProjectNamespace.Pages; public partial class Index : ComponentBase { [Inject] private MainWindow _mainWindow { get; set; } = null!; private string inputValue1 = string.Empty; private string selectedCategory = string.Empty; private async Task HandleSubmit() { if (string.IsNullOrWhiteSpace(inputValue1) || string.IsNullOrWhiteSpace(selectedCategory)) return; await _mainWindow.AddShoppingItem(inputValue1, selectedCategory); // 清空输入 inputValue1 = string.Empty; selectedCategory = string.Empty; } }
注:Index.razor的UI部分与方案一完全一致。
注意事项
- 确保项目已安装对应的数据库NuGet包:SQL Server用
Microsoft.Data.SqlClient,SQLite用Microsoft.Data.Sqlite - 生产环境中,连接字符串应存储在
appsettings.json而非硬编码,可通过IConfiguration读取 - 可根据需求添加更多验证逻辑(如商品名称重复检查)或用户反馈(如提交成功提示)
内容的提问来源于stack exchange,提问作者Ole M
相关产品推荐
相关产品推荐

