Reputation: 485
I have two controls on my form(control1 and control2) that are located next to the each other. The width of control1 is variable.
Can I bind the Left Property of control2 to the width property of control1?
I wrote below code but it didn't work:
control2.DataBindings.Add(new Binding("Left", control1, "Width"));
Upvotes: 2
Views: 2493
Reputation: 398
The simplest way to handle this I think is by EventHandlers:
public Form1()
{
InitializeComponent();
panel2.SizeChanged +=panel2_SizeChanged;
}
private void button1_Click(object sender, EventArgs e)
{
panel2.Size = new Size(panel2.Size.Width * 2, panel2.Size.Height * 2);
}
void panel2_SizeChanged(object sender, EventArgs e)
{
panel1.Size = panel2.Size;
}
Upvotes: 1
Reputation: 73502
control2.DataBindings.Add(new Binding("Left", control1, "Width"));//Your code
Your code doesn't work because there is no change notification going when chaning Width
property, but Size
does.
You can bind to Size
but the problem is you need an int
but Size property is of type Size
, so you need to convert it also using Format event like this.
var binding = new Binding("Left", control1, "Size", true,DataSourceUpdateMode.Never);
binding.Format += (sender, args) =>
{
if (args.DesiredType == typeof (int))
{
Size size = (Size) args.Value;
args.Value = size.Width;
}
};
control2.DataBindings.Add(binding);
Another way is to implement INotifyPropertyChanged
in your source control. That should do the trick.
Upvotes: 2
Reputation: 398
It needs to implement INotifyPropertyChanged interface.
I look more deeper and it has three options
public enum DataSourceUpdateMode
{
OnValidation,
OnPropertyChanged,
Never
}
Default is OnValidation, but the Width doesn't cause neither Validation neither PropertyChanged
An example of usage:
panel1.DataBindings.Add(new Binding("Width", panel2, "Width", false, DataSourceUpdateMode.OnPropertyChanged));
Upvotes: 0
Reputation: 19618
You can do that. Here is a snippet in this I am binding trackbar value to width of button
button1.DataBindings.Add(new Binding("width", trackBar1, "value"));
I tried with Textbox also, it is also working.
button1.DataBindings.Add(new Binding("left", textBox1, "Text"));
Upvotes: 0