Winforms data binding a control to an element of an array at specific index

时间:2016-07-11 19:46:52

标签: c# winforms data-binding

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 个答案:

答案 0 :(得分:1)

如果要将控件绑定到数组的元素,而不是尝试直接绑定到该元素,请将控件绑定到该数组,然后将PositionCurrencyManager设置为数组中该元素的索引。

例如,下面的代码将NumericUpDown绑定到数组并显示30,即索引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;
}

可以使用BindingSource完成相同的绑定。将array设置为绑定源的DataSource并使用绑定源进行数据绑定就足够了。然后,要显示特定元素,请设置Position的{​​{1}}。