let's say I've got this code (in Winforms):
public class SomeClass
{
public string Name { get; set; }
}
public partial class SomeControl : UserControl
{
private SomeClass inClass;
public string MyName { get; set; }
public SomeControl(SomeClass someClass)
{
InitializeComponent();
this.inClass = someClass;
SetupBinding();
}
private void SetupBinding()
{
this.DataBindings.Clear();
this.DataBindings.Add("MyName", this.inClass, "Name");
}
}
If I'll change the the value of SomeClass.Name outside the user control, the property MyName never changes. What am I doing wrong?
Thank you
SomeClass must impelement INotifyPropertyChanged or have event named NameChanged if you want bidirectional data binding. You can implement it yourself, but I highly recommend Fody.PropertyChanged project.
PS: I wrote some extension method to create binding more easier and refactoring friendly way. In your case it would look like this:
this.BindTo(inClass, c => c.MyName , m => m.Name);
The method itself:
public static class BindingExtensions
{
public static Binding BindTo<TControl, TControlProperty, TModel, TModelProperty>(this TControl control, TModel model, Expression<Func<TControl, TControlProperty>> controlProperty, Expression<Func<TModel, TModelProperty>> modelProperty, string format = null)
where TControl : Control
{
var controlPropertyName = ((MemberExpression)controlProperty.Body).Member.Name;
var modelPropertyName = ((MemberExpression)modelProperty.Body).Member.Name;
var formattingEnabled = !string.IsNullOrWhiteSpace(format);
var binding = control.DataBindings.Add(controlPropertyName, model, modelPropertyName, formattingEnabled, DataSourceUpdateMode.OnPropertyChanged);
if (formattingEnabled)
{
binding.FormatString = format;
}
return binding;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.