我正在尝试使用System.Windows.Forms.PropertyGrid
.
要使属性在此网格中不可见,应使用BrowsableAttribute
set to false
。但是添加此属性会使该属性不可绑定。
示例:创建一个新的 Windows 窗体项目,然后将 aTextBox
和拖放PropertyGrid
到Form1
. 使用下面的代码, 的宽度TextBox
不会绑定到Data.Width
:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Data data = new Data();
data.Text = "qwe";
data.Width = 500;
BindingSource bindingSource = new BindingSource();
bindingSource.Add(data);
textBox1.DataBindings.Add("Text", bindingSource, "Text", true,
DataSourceUpdateMode.OnPropertyChanged);
textBox1.DataBindings.Add("Width", bindingSource, "Width", true,
DataSourceUpdateMode.OnPropertyChanged);
propertyGrid1.SelectedObject = data;
}
}
数据类的代码是:
public class Data : IBindableComponent
{
public event EventHandler TextChanged;
private string _Text;
[Browsable(true)]
public string Text
{
get
{
return _Text;
}
set
{
_Text = value;
if (TextChanged != null)
TextChanged(this, EventArgs.Empty);
}
}
public event EventHandler WidthChanged;
private int _Width;
[Browsable(false)]
public int Width
{
get
{
return _Width;
}
set
{
_Width = value;
if (WidthChanged != null)
WidthChanged(this, EventArgs.Empty);
}
}
#region IBindableComponent Members
private BindingContext _BindingContext;
public BindingContext BindingContext
{
get
{
if (_BindingContext == null)
_BindingContext = new BindingContext();
return _BindingContext;
}
set
{
_BindingContext = value;
}
}
private ControlBindingsCollection _DataBindings;
public ControlBindingsCollection DataBindings
{
get
{
if (_DataBindings == null)
_DataBindings = new ControlBindingsCollection(this);
return _DataBindings;
}
}
#endregion
#region IComponent Members
public event EventHandler Disposed;
public System.ComponentModel.ISite Site
{
get
{
return null;
}
set
{
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
throw new NotImplementedException();
}
#endregion
}
如果在 Data 中的每个属性上将 Browsable 属性切换为 true,它就可以工作。现在似乎 BindingSource 通过 Browsable 属性搜索数据源。