首页 > 解决方案 > 从 System.windows.FormsMessageBox 转换为 Xceed.Wpf.Toolkit.MessageBox 时如何处理 system.InvalidOperationException

问题描述

我有一个非常平淡的消息框问我的用户一个简单的问题(不是是或否)。为了快速开发,我使用了一个简单的 System.Windows.Forms.MessageBox 并提出了问题(“如果你想选择'A',请点击'是',如果你想选择'B',请点击'否'”)。现在我要回去改进我的 wpf 应用程序的外观和感觉,我一直试图将这个 MessageBox 转换成看起来不错的东西。

我的初步搜索告诉我使用Xceed.Wpf.Toolkit.MessageBox能够创建自定义消息框,但是当我尝试使用它时出现异常。

旧代码

DialogResult dialogResultForDataDisplay = System.Windows.Forms.MessageBox.Show("Yes: Display by properties \n \t Each row will contain data for a specific asset class in a specific submarket during a specific quarter. \n \n No: Display by quarters \n \t Each row will will show the change over time for a specific property of an asset class in a specific submarket.", "Data Grouping Format", MessageBoxButtons.YesNo);

新代码

Style style = new Style();
style.Setters.Add(new Setter(Xceed.Wpf.Toolkit.MessageBox.YesButtonContentProperty, "By Property"));
style.Setters.Add(new Setter(Xceed.Wpf.Toolkit.MessageBox.NoButtonContentProperty, "By Quarter"));
MessageBoxResult result = Xceed.Wpf.Toolkit.MessageBox.Show("How do you want your information displayed?", "My caption", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.Yes, style);
        Console.WriteLine(result);

新代码正在生成此异常:System.InvalidOperationException: 'The calling thread must be STA, because many UI components require this.'

你将如何处理这个异常?

标签: messageboxxceed

解决方案


我现在发现的一个解决方案是在调用方法中敲击它。如果有人有更好的解决方案,请发布。

MessageBoxResult result = MessageBoxResult.None;
System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate
{
    Style style = new Style();
    style.Setters.Add(new Setter(Xceed.Wpf.Toolkit.MessageBox.YesButtonContentProperty, "Yes, FTW!"));
    style.Setters.Add(new Setter(Xceed.Wpf.Toolkit.MessageBox.NoButtonContentProperty, "Omg, no"));
    result = Xceed.Wpf.Toolkit.MessageBox.Show("How do you want your information displayed?", "My caption", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.Yes, style);
}
Console.WriteLine(result);

推荐阅读