سؤال

I have simple Windows Forms application (not WPF), and I have two controls on it:

  1. TrackBar
  2. NumericUpDown

I want to make some binding between them so if one of them has its value change, the other control will be updated to show the same value.

Is this possible? If so, how can I do it?

Thanks.

هل كانت مفيدة؟

المحلول

Sure, it's possible. I don't know of any way to make the connection between the two controls automatic, so you'll have the write the code yourself. But don't worry, it's not difficult.

You'll first need to attach a handler to the event that is raised by each control when its value changes. Logically enough, both controls this event the same thing: ValueChanged. Then, in each event handler method, you can programmatically set the value of the other control to the new value of the first control. For example:

void myNumericUpDown_ValueChanged(object sender, EventArgs e)
{
    // Sync up the trackbar with the value just entered in the spinbox
    myTrackBar.Value = Convert.ToInt32(myNumericUpDown.Value);
}

void myTrackBar_ValueChanged(object sender, EventArgs e)
{
    // Sync up the spinbox with the value just set on the trackbar
    myNumericUpDown.Value = myTrackBar.Value;
}

Obviously for this to work correctly, you either need to make sure that the controls have the same range (maximum and minimum values), or add some error checks to the above code.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top