如何在WPF应用中安装Monaco编辑器?
WPF中安装使用Monaco编辑器的正确方案
Monaco本质是Web组件,不能直接套用Windows Forms的安装方式在WPF中部署,正确做法是通过WebView2控件承载它,步骤如下:
安装WebView2依赖
在NuGet包管理器中搜索并安装Microsoft.Web.WebView2,这是WPF承载Web内容的必要组件。如果遇到运行时缺失问题,可额外安装对应平台的Microsoft.Web.WebView2.Runtime.*包。在XAML中添加WebView2控件
把WebView2嵌入到你的WPF窗口布局里:<Window x:Class="YourNamespace.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wpf="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf" Height="600" Width="800"> <Grid> <wpf:WebView2 x:Name="MonacoHost" /> </Grid> </Window>加载Monaco编辑器
在后台代码中初始化WebView2并加载Monaco,推荐使用CDN快速部署:using Microsoft.Web.WebView2.Core; using System.Windows; namespace YourNamespace { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); _ = LoadMonacoEditor(); } private async System.Threading.Tasks.Task LoadMonacoEditor() { // 确保WebView2核心初始化完成 await MonacoHost.EnsureCoreWebView2Async(null); // 构造包含Monaco的HTML内容 var monacoHtml = @" <!DOCTYPE html> <html> <head> <meta charset='UTF-8'> <script src='https://cdn.jsdelivr.net/npm/monaco-editor@latest/min/vs/loader.js'></script> </head> <body style='margin:0; padding:0'> <div id='editor-container' style='width:100%; height:100vh'></div> <script> require.config({ paths: { 'vs': 'https://cdn.jsdelivr.net/npm/monaco-editor@latest/min/vs' }}); require(['vs/editor/editor.main'], function() { // 创建Monaco编辑器实例 const editor = monaco.editor.create(document.getElementById('editor-container'), { value: '// 开始编写你的代码', language: 'csharp', // 可切换为javascript、python等 theme: 'vs-dark' }); }); </script> </body> </html>"; // 加载HTML内容到WebView2 MonacoHost.NavigateToString(monacoHtml); } } }本地部署替代方案(无网络场景)
- 从npm下载Monaco包:
npm install monaco-editor - 将
node_modules/monaco-editor/min/vs文件夹复制到WPF项目中,设置文件夹内所有文件的“复制到输出目录”为“如果较新则复制” - 修改HTML中的资源路径为本地路径:
<script src='vs/loader.js'></script> <script> require.config({ paths: { 'vs': 'vs' }}); // 其余代码不变 </script>
- 从npm下载Monaco包:
内容的提问来源于stack exchange,提问作者gambling addict
相关产品推荐
相关产品推荐

