WPF Glimps——WPF 的调试器可视化工具






4.10/5 (7投票s)
2007年11月15日
2分钟阅读

47365

782
一个调试器可视化工具,

引言
WpfVisualVisualizer
"Glimps" 允许你在 Visual Studio 调试器中预览 WPF 控件,同时逐步执行应用程序代码,从而更容易调试复杂的 WPF 用户界面。

Josh Smith 已经编写了一个出色的调试器可视化工具,可以让你检查 WPF 元素的属性,可以在 这里 找到。
背景
在 WPF 应用程序中,通常有很多视觉元素。 当你调试时,很难知道哪个视觉元素被某个变量引用。
WpfVisualVisualizer
将 Visual 或 Control 渲染成一个小图像,你可以在调试器中预览它。 这适用于任何类型的 Visual,甚至是视频或 3D,一旦它被初始化和加载。
部署 Glimps
请参阅 Josh Smith 的文章,了解如何部署 Visual Studio 调试器可视化工具 这里。 无论如何,这是一篇很棒的文章。
如何使用它
安装 Glimps 后,如果你将鼠标悬停在调试器中的 WPF 视觉元素上,就可以从工具提示中选择它,如页面顶部的屏幕截图所示。
限制
UIElements
和 FrameworkElements
必须先初始化和加载,然后才能显示。 因此,当你将断点放在构造函数中时,你将看不到任何内容。
工作原理
调试器可视化工具由两部分组成
第一部分 (IVisualizerObjectProvider
) 在你的应用程序的进程中运行。 这部分负责收集和序列化将在 Visual Studio 中显示的所需信息。
第二部分 (DialogDebuggerVisualizer
) 在 Visual Studio 调试器中运行,并负责显示信息。 这是实际的可视化工具。
为了将 WPF 视觉元素显示为 Visual Studio 中的缩略图图像,它必须在应用程序的上下文中渲染为位图,然后转换为 GDI 图像。 这将通过线路发送到可视化工具,它是一个简单的 WinForms 对话框。
DebuggerVisualizer
通过调用 ObjectProvider
上的 GetData
方法来请求它将可视化的数据。 GetData
返回一个 Stream
,其中包含序列化数据。
可视化工具和对象提供程序紧密耦合,因此可视化工具知道 Stream
包含一个图像,并将其显示在 PictureBox
中
// Display the visual in Visual Studio
protected override void Show(IDialogVisualizerService windowService,
IVisualizerObjectProvider objectProvider)
{
// read the serialized (GDI-)image from the stream
Stream s = objectProvider.GetData();
Image image = Image.FromStream(s);
// prepare the form
Form form = new Form();
form.Text = "WPF Visual";
form.ClientSize = new DrawingSize
(WpfVisualObjectSource.MaxSize.Width, image.Height);
form.FormBorderStyle = FormBorderStyle.FixedToolWindow;
if (image != null)
{
PictureBox pictureBox = new PictureBox();
pictureBox.Image = image;
pictureBox.Parent = form;
pictureBox.Dock = DockStyle.Fill;
form.Controls.Add(pictureBox);
}
// show the form
windowService.ShowDialog(form);
}
在 ObjectProvider
方面,目标 WPF 视觉元素需要渲染为 BitmapSource
,然后转换为我们可以在 WinForms 中显示的 GDI 图像
// create image data from WPF visual
public override void GetData(object target, Stream outgoingData)
{
Image img = null;
// target is a bitmap source: convert it to a GDI image
if (target is BitmapSource)
{
img = BitmapSourceToGdiImage((BitmapSource)target);
}
if (target is FrameworkElement)
{
FrameworkElement fe = (FrameworkElement)target;
if (!fe.IsLoaded) img = CreateEmptyBitmap();
}
// target is a visual: render it to a RenderTargetBitmap and
// convert to GDI
if (img==null && target is Visual)
{
BitmapSource bmpSource = CreateBitmapSource((Visual)target);
img = BitmapSourceToGdiImage(bmpSource);
}
if (img == null) img = new Bitmap(0, 0);
// save image to stream and dispose of GDI image
img.Save(outgoingData, ImageFormat.Bmp);
img.Dispose();
}
历史
- 2007 年 11 月 15 日 - 上传第一个版本
- 2007 年 11 月 16 日 - Josh Smith 将 Glimps 添加到 Woodstock for WPF,并且还在代码中进行了一些改进。 他很友善地把我添加为作者。