Windows 窗体中的 UserControl 可让您创建更复杂的作品。
public class MyUserControl : UserControl
{
public MyUserControl()
{
IniitalizeComponents();
}
private void InitializeComponents()
{
this.datagridview1 = new System.Windows.Form.DataGridView();
this.Controls.Add(this.dataGridView1);
}
private System.Windows.Forms.DataGridView dataGridView1;
}
非常直接。但是,有时您希望公开该内部控制的元素。所以就像我可以在我的用户控件上放置一个“数据源”并将其连接到 dataGridView1。
public object DataSource {get => dataGridView1.DataSource; set => dataGridView1.DataSource = value;}
我什至可以,如果我不想手动公开嵌入控件的每个属性,我可以通过引用的属性公开控件:
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public DataGridView GridControl => this.dataGridView1;
问题在于它暴露了控件的所有属性和事件。
输入自定义设计器。
[Designer(typeof(MyDGVDesigner)]
public class CustomDataGridView : DataGridView
{
}
class MyDGVDesigner : ControlDesigner
{
protected override PreFilterProperties(IDictionary properties)
{
properties.Remove(nameof(DataGridView.DataSource));
}
}
现在我的 UserControl 公开的“网格”不再显示 DataSource 属性。
然而,这就是问题所在。在设计我的 UserControl 时,私有字段的属性也是隐藏的。我想在“GridControl”属性级别“限制”公开给 ProperyGrid 的属性/事件,以便在将 UserControl 从外部添加到表单时,而不是在我操作私有 dataGridView1 的 UserControl 的表单设计器中。
这甚至可能吗?如果是这样,我将如何实现它?