WinUI3中ContentDialog的SecondaryButtonCommand该如何设置?
解决方案
因为你的错误对话框是在静态工具类中创建的,不需要依赖MVVM Toolkit的RelayCommand,自己实现一个极简的ICommand就能满足需求,步骤如下:
1. 实现轻量版ICommand类
添加一个仅处理核心逻辑的命令类,按钮始终保持可用状态:
public class SimpleCommand : ICommand { private readonly Action _execute; public SimpleCommand(Action execute) { _execute = execute ?? throw new ArgumentNullException(nameof(execute)); } public event EventHandler? CanExecuteChanged; public bool CanExecute(object? parameter) => true; public void Execute(object? parameter) => _execute(); }
2. 修改ErrorDialog的Show方法
把复制剪贴板的逻辑绑定到按钮命令中,替换原代码里的??????:
using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using System; using Windows.ApplicationModel.DataTransfer; namespace JimPrototypes2.Helpers { public static class ErrorDialog { public static void Show(XamlRoot root, string message, string stackTrace) { string msg = message + Environment.NewLine + Environment.NewLine + stackTrace; ContentDialog err = new ContentDialog() { XamlRoot = root, Title = "An Error Has Occured", Content = msg, CloseButtonText = "Ok", SecondaryButtonText = "Copy Error", // 绑定命令,点击按钮时执行复制逻辑 SecondaryButtonCommand = new SimpleCommand(() => { DataPackage package = new DataPackage(); package.SetText(msg); Clipboard.SetContent(package); }) }; _ = err.ShowAsync(); } } // 嵌入SimpleCommand实现 public class SimpleCommand : ICommand { private readonly Action _execute; public SimpleCommand(Action execute) { _execute = execute ?? throw new ArgumentNullException(nameof(execute)); } public event EventHandler? CanExecuteChanged; public bool CanExecute(object? parameter) => true; public void Execute(object? parameter) => _execute(); } }
说明
- 这个
SimpleCommand只处理最基础的命令触发逻辑,比引入MVVM框架更轻量,适合这种工具类场景。 - 点击「Copy Error」按钮时,会自动执行剪贴板复制逻辑,把完整错误文本复制到系统剪贴板。
- 用
_ =忽略ShowAsync()的返回值,避免编译器警告。
内容的提问来源于stack exchange,提问作者Jim D
相关产品推荐
相关产品推荐

