我想在运行时在GUI中显示任意对象的公共属性/值。c#winform在运行时检查对象
是否有一个winform允许用户查看调试模式下的任何对象的内容?该对象将包含许多字典>,并且能够在运行时扩展和查看这些列表的内容将会很好。
如果不可用,有没有办法实现类似的功能?
感谢
我想在运行时在GUI中显示任意对象的公共属性/值。c#winform在运行时检查对象
是否有一个winform允许用户查看调试模式下的任何对象的内容?该对象将包含许多字典>,并且能够在运行时扩展和查看这些列表的内容将会很好。
如果不可用,有没有办法实现类似的功能?
感谢
有PropertyGrid
:
var form = new Form();
form.Controls.Add
(
new PropertyGrid()
{
SelectedObject = new { A = "Hi", B = new [] { 32, 40 } }
}
);
form.Show();
这是从如何调试一个作品很远,但它可以很容易地修改,以处理您的任何特殊情况。
所有你需要做的就是创建一个带有PropertyGrid的窗体。然后设置选定的对象。
using xxx.CFM.UI.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace xxx.CFM.UI.Forms
{
/// <summary>
/// Form used to inspect objects at runtime
/// </summary>
public partial class frmInspector : BaseForm
{
#region Properties
/// <summary>
/// Gets or Sets the
/// </summary>
public object SelectedObject
{
get { return propertyGrid.SelectedObject; }
set { propertyGrid.SelectedObject = value; }
}
#endregion Properties
#region Constructor
/// <summary>
/// Constructor
/// </summary>
public frmInspector(object objectToInspect)
{
try
{
InitializeComponent();
this.SelectedObject = objectToInspect;
}
catch (Exception ex)
{
UIMessage.DisplayError(ex);
}
}
#endregion Constructor
#region Events
/// <summary>
/// Closes the form
/// </summary>
/// <param name="sender">object</param>
/// <param name="e">args</param>
private void btnClose_Click(object sender, EventArgs e)
{
try
{
this.Close();
}
catch (Exception ex)
{
UIMessage.DisplayError(ex);
}
}
#endregion Events
}
}
我在例如网格使用上下文菜单上的期望它下面的数据记录:
/// <summary>
/// Opens the object inspector
/// </summary>
/// <param name="sender">object</param>
/// <param name="e">args</param>
private void inspectorMenuItem_Click(object sender, EventArgs e)
{
try
{
//Get the payload
SectionDataTreeListMenuItemPayload payload = (sender as ToolStripMenuItem).Tag as SectionDataTreeListMenuItemPayload;
if (payload == null || payload.DataRow == null)
return;
using (frmInspector frmInspector = new frmInspector(payload.DataRow))
frmInspector.ShowDialog();
}
catch (Exception ex)
{
UIMessage.DisplayError(ex);
}
}
另一个小窍门,你所能做的就是确保表单仅当通过使用“编译器指令”使用下面的代码在调试模式下构建时才可用。 (如果你希望它只用于调试当然)
#if DEBUG
//Add object inspector menu item if built in debug mode
ToolStripMenuItem inspectorMenuItem = new ToolStripMenuItem();
inspectorMenuItem.Text = "Inspect Object";
inspectorMenuItem.Image = Properties.Resources.Inspect24x24;
inspectorMenuItem.Click += inspectorMenuItem_Click;
inspectorMenuItem.Tag = payload;
contextMenuStrip.Items.Add(inspectorMenuItem);
#endif
使用'PropertyGrid'控件。 – Yegor