How can I bind to a programmatic property in .NET?
I have a form with a programmatic property called SelectedAccessGroups
:
[Bindable(true)]
public string SelectedAccessGroups
{
get { return "Selected Access Groups here"; }
}
I also have a BindingSource
on the form which has a field called EditableByAccessGroups
. I would like to bind my SelectedAccessGroups
property to that field.
I attempted the following in my form's constructor, but it doesn't work:
this.DataBindings.Add(new System.Windows.Forms.Binding("SelectedAccessGroups",
this.CriteriaBindingSource, "EditableByAccessGroups"));
Is there a way to accomplish this?
Thanks!
Update: The error I was getting when attempting to run my program was quite undescriptive, but looking into it further, I fo开发者_JAVA百科und that I was getting the error because my property was read-only. I added a blank setter to the property, and the binding works fine now.
You have to implement INotifyPropertyChanged on your class so the bound items will know when something is different. here is an msdn article and there are several other articles out there that will help as well in implementing this interface.
http://msdn.microsoft.com/en-us/library/ms743695.aspx
Per your update and change of the question, to get one-way binding you could use use one of the other Binding constructors that takes DataSourceUpdateMode as a parameter.
http://msdn.microsoft.com/en-us/library/system.windows.forms.binding.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.datasourceupdatemode.aspx
Rather than add the cruft of a blank setter, try using the overloaded constructor of Binding that takes a DataSourceUpdateMode value and passing DatasourceUpdateMode.Never. This will prevent the binding from attempting to update the datasource from the control.
精彩评论