我正在创建一个通用的异常消息对话框,并且想要有一个“复制错误”按钮来将错误文本复制到剪贴板。我不知道SecondaryButtonCommand = ICommand 的用途。
我所有关于使用 WinUI 3 实现 ICommand 的研究最终都以 RelayCommand 和 MVVM Toolkit 的某些变体为基础,但我无法开始工作。
我可以使用“复制到剪贴板”功能。我现在希望当用户单击对话框上的按钮时发生这种情况。
请注意,此对话框是在代码中其自己的类中创建的,旨在从任何页面使用。
SecondaryButtonCommand = ???
我该用什么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 = ???????
};
err.ShowAsync();
// Just testing copy to clipboard
DataPackage package = new DataPackage();
package.SetText(msg);
Clipboard.SetContent(package);
}
}
}
最终遇到了一个有帮助的 ICommand 示例。当我看到一个简单、实用的示例后,发现它真的很容易。
这是我的 ICommand,名为 CopyCommand
using System;
using System.Windows.Input;
using Windows.ApplicationModel.DataTransfer;
namespace JimPrototypes2.Helpers
{
class CopyCommand : ICommand
{
string _copyText;
public CopyCommand(string input)
{
_copyText = input;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
DataPackage package = new DataPackage();
package.SetText(_copyText);
Clipboard.SetContent(package);
}
public event EventHandler CanExecuteChanged;
}
}
我更新的 ErrorDialog 类
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System;
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;
CopyCommand cmd = new CopyCommand(msg);
ContentDialog err = new ContentDialog()
{
XamlRoot = root,
Title = "An Error Has Occured",
Content = msg,
CloseButtonText = "Ok",
SecondaryButtonText = "Copy Error",
SecondaryButtonCommand = cmd
};
err.ShowAsync();
}
}
}
并在BackgroundWorker线程的try catch块中使用它
private void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
_backup.Backup(_folders);
}
catch (Exception ex)
{
DispatcherQueue.TryEnqueue(() => {
ErrorDialog.Show(this.XamlRoot, ex.Message, ex.StackTrace);
});
}
}