Winforms 数据将控件绑定到特定索引处的数组元素 [英] Winforms data binding a control to an element of an array at specific index

查看:33
本文介绍了Winforms 数据将控件绑定到特定索引处的数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 numericupdown 和数组元素之间创建数据绑定.在我的表单中,我尝试创建如下所示的绑定,但它似乎不起作用.任何帮助将不胜感激.

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.

绑定:

nudTest.DataBindings.Add("Value", eac.ESettings.HsvArray[0], "", false,DataSourceUpdateMode.OnPropertyChanged);

数组:

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));
        }
    }
}

推荐答案

当你想把一个控件绑定到数组的某个元素上,而不是试图直接绑定到元素上,将控件绑定到数组,然后再设置"nofollow">CurrencyManager 到该元素在数组中的索引.

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.

例如,下面的代码将 NumericUpDown 绑定到数组并显示 30,即索引 2 处的元素:

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;
}

可以使用 BindingSource 完成相同的绑定.将array设置为绑定源的DataSource,使用绑定源进行数据绑定就足够了.然后要显示特定元素,设置 BindingSourcePosition.

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.

这篇关于Winforms 数据将控件绑定到特定索引处的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆