当我从单元测试中运行 ShowDialog 调用时,我得到了一个
System.Windows.Markup.XamlParseException: The current SynchronizationContext may not be used as a task scheduler.
从 main 运行正常。我意识到这不是测试仪的正常使用,但能够选择一个对话框并单击一个按钮以使用测试数据运行它以查看该对话框是否有效是很有值(value)的。但是这个错误阻止我运行它。
在“正确的”线程上运行对话代码是否有技巧?
这是单元测试代码:
[Fact]
static public void Draw2()
{
var uiThread = new Thread(Draw20);
uiThread.SetApartmentState(ApartmentState.STA);
uiThread.Start();
// Wait for the UI thread to finish
uiThread.Join();
}
static void Draw20()
{
ModernUIApp1.MainWindow window = new MainWindow();
System.Windows.Forms.Integration
.ElementHost
.EnableModelessKeyboardInterop(window);
window.ShowDialog();
window = null;
}
窗口代码: >
<mui:ModernWindow.MenuLinkGroups>
<mui:LinkGroup DisplayName="welcome">
<mui:LinkGroup.Links>
<mui:Link DisplayName="home" Source="/Pages/Home.xaml" />
<mui:Link DisplayName="my page" Source="/Pages/BasicPage.xaml" />
</mui:LinkGroup.Links>
</mui:LinkGroup>
<mui:LinkGroup DisplayName="settings" GroupName="settings">
<mui:LinkGroup.Links>
<mui:Link DisplayName="software" Source="/Pages/Settings.xaml" />
</mui:LinkGroup.Links>
</mui:LinkGroup>
</mui:ModernWindow.MenuLinkGroups>
<mui:ModernWindow.TitleLinks>
<mui:Link DisplayName="settings" Source="/Pages/Settings.xaml" />
</mui:ModernWindow.TitleLinks>
</mui:ModernWindow>
最佳答案
为了从单元测试中显示 WPF UI,您需要生成一个新线程,确保它是 single-threaded apartment (STA) ,从该线程创建 UI,显示对话框,然后将结果编码回单元测试线程。
var uiThread = new Thread(MyCreateAndShowUIFunction);
uiThread.SetApartmentState(ApartmentState.STA);
uiThread.Start();
...
// Wait for the UI thread to finish
uiThread.Join();
总的来说,单元测试并不是为了实际启动 UI。那将是一个集成测试,甚至是一个编码的 UI 测试。
关于c# - 从测试运行 WPF 对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19760818/