问题
I am attempting to create a databinding between a numericupdown and an array element. In my form I have tried creating the binding shown below, but it doesn't seem to work. Any help would be appreciated.
Binding:
nudTest.DataBindings.Add("Value", eac.ESettings.HsvArray[0], "", false,DataSourceUpdateMode.OnPropertyChanged);
Array:
public class ESettings : INotifyPropertyChanged
{
private int[] hsvArray = new int[6];
public event PropertyChangedEventHandler PropertyChanged;
[XmlIgnore]
public bool PrgVarIsDirty
{
get { return prgVarIsDirty; }
set
{
prgVarIsDirty = value;
OnPropertyChanged("PrgVarIsDirty");
}
}
public int[] HsvArray
{
get { return hsvArray; }
set
{
if (value != hsvArray)
{
prgVarIsDirty = true;
hsvArray = value;
OnPropertyChanged("HsvArray");
}
}
}
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
回答1:
When you want to bind a control to an element of an array, instead of trying to bind directly to the element, bind control to the array, and then set the Position of CurrencyManager to the index of that element in the array.
For example, below code binds the NumericUpDown to array and shows 30, the element at index 2:
int[] array = new int[] { 10, 20, 30, 40 };
private void Form1_Load(object sender, EventArgs e)
{
this.numericUpDown1.DataBindings.Add("Value", array, "");
((BindingManagerBase)this.numericUpDown1.BindingContext[array]).Position = 2;
}
The same binding could be done using BindingSource. It's enough to set array as DataSource of the binding source and use the binding source for data binding. Then to show a specific element, set Position of BindingSource.
来源:https://stackoverflow.com/questions/38315007/winforms-data-binding-a-control-to-an-element-of-an-array-at-specific-index