您可以在運行時通過手動註冊TypeDescriptor來設置類型元數據類型。
這就像這樣。
var type = typeof(Foo);
var metadataType = typeof(FooMetadata);
TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(type, metadataType), type);
要在上下文中顯示所有內容,這將顯示數據網格中帶有標題「自定義欄」的單個列。
public class Foo
{
public string Bar { get; set; }
public string DontShowMe { get; set; }
}
public class FooMetadata
{
[DisplayName("Custom Bar")]
public string Bar { get; set; }
[Browsable(false)]
public string DontShowMe { get; set; }
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var type = typeof(Foo);
var metadataType = typeof(FooMetadata);
TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(type, metadataType), type);
this.dataGridView1.DataSource = new List<Foo> { new Foo { Bar = "Foobar" } };
}
}
,如果你想切換的元數據類型在路上,但請記住,設置/取消設置它適用於整個應用領域等線程需要被考慮的也是TypeDescriptor.RemoveProviderTransparent
。
我可以。它只是需要很多難以管理的代碼,而複雜的查詢會導致一陣痛苦。 – elyashiv
但是,你可能會添加一個模塊到你的軟件,專門管理這些東西...... –