我想在winform应用程序中设计一个类似visual studio的属性窗口的面板。 事实上,我希望有一个可以接受组合框作为其单元格的网格,因此用户可以选择其中一个项而不是键入。
我知道在wpf中有可能但是我想知道在winform应用程序中是否有任何方法可以做到这一点?
修改 我正在寻找一种在FooProperty前面this example显示FooForm结果的方法。
注意:我不能在这里放置我的真实应用程序的屏幕截图!但我在我的属性网格中有类似下面的图片,我想显示所选背景图像的名称作为BackgroudImage属性的值,该属性在红色矩形而不是(无)值中指定。
请告诉我是否有办法做到这一点?
答案 0 :(得分:3)
您可以使用System.Windows.Forms.PropertyGrid控件。你会在互联网上找到很多例子。
答案 1 :(得分:2)
可以通过PropertyGrid
提供网格;这使用了System.ComponentModel
实现,它非常灵活但非常复杂。但是,要提供建议值,请使用GetStandardValues
TypeConverter
方法。完整的例子:
(修改:需要CanConvertFrom
/ ConvertFrom
才能作为组合使用)
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public class MyType
{
[TypeConverter(typeof(GiveMeOptionsConverter))]
public string SomeProperty {get;set;}
private class GiveMeOptionsConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string) return value;
return base.ConvertFrom(context, culture, value);
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false; // true is drop-down; false is combo
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
// this gives you the `MyType` instance if you need it
var obj = (MyType)context.Instance;
return new StandardValuesCollection(
new[] { "abc", "def", "ghi" });
}
}
}
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using (var grid = new PropertyGrid {
Dock = DockStyle.Fill,
SelectedObject = new MyType()
})
using (var form = new Form { Controls = { grid } })
{
Application.Run(form);
}
}
}
}
答案 2 :(得分:1)
您可以使用PropertyGrid和自定义类型编辑器来执行此操作。
在这里,您可以详细说明如何使用属性网格,以及如何使用自定义UI类型编辑器。