bind listbox to index C#

馋奶兔 提交于 2019-12-06 14:45:51

Make sure you implement INotifyPropertyChanged in RunScript class. Here's a complete sample:

class RunScript : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private int scriptCounter;

    private ISynchronizeInvoke invoker;
    public RunScript(ISynchronizeInvoke invoker)
    {
        if (invoker == null) throw new ArgumentNullException("invoker");
        this.invoker = invoker;
    }

    public async void RunScriptList()
    {
        ScriptCounter = 0;
        foreach (var cell in Enumerable.Range(1, 15))
        {
            ScriptCounter++;
            await Task.Delay(1000);
            //DoSomething
        }
    }

    public int ScriptCounter
    {
        get { return scriptCounter; }
        set
        {
            scriptCounter = value;
            OnPropertyChanged();
        }
    }

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            Action action = () => handler(this, new PropertyChangedEventArgs(propertyName));
            invoker.Invoke(action, null);
        }
    }
}

private RunScript rs;
public Form1()
{
    InitializeComponent();

    rs = new RunScript(this)

    var binding = new Binding("SelectedIndex", rs, "ScriptCounter", false, DataSourceUpdateMode.OnPropertyChanged);
    listBox1.DataBindings.Add(binding);
}

private void button1_Click(object sender, EventArgs e)
{
    rs.RunScriptList();
}

Note I have used async/await in RunScriptList, If you do it in another thread you need to fire PropertyChanged event in main thread to avoid cross thread exception.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!