Csharp/C#教程:绑定列表框以索引C#分享


绑定列表框以索引C#

我不知道是否可能,但我想要的是类似的东西在WinForm listbox1有一个行列表(从文件复制)

在另一个Thread和类中,我在一个List上运行,该列包含我解析的每一行相同的行和DoSomething一旦我完成该行,我希望列表框中的索引改变

根据我的基本和有限的理解,我的方法是使用一个Event来激活forms,而不是使用Invoke(不用于交叉线程)

有没有办法以某种方式以我的for/foreach循环以某种方式绑定到listbox索引?

 class form { listBoxScript.SetSelected(ScriptCounter, true);<--bind the ScriptCounter? } 

在另一个class级

 class RunScript { //.. public void RunScriptList() { ScriptCounter = 0 ; foreach ( var cell in ScriptList) { ScriptCounter ++; //DoSomething } } } 

确保在RunScript类中实现INotifyPropertyChanged 。 这是一个完整的示例:

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

注意我在RunScriptList使用了async/await ,如果你在另一个线程中执行它,你需要在主线程中触发PropertyChanged事件以避免跨线程exception。

上述就是C#学习教程:绑定列表框以索引C#分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1029046.html

(0)
上一篇 2022年1月12日
下一篇 2022年1月12日

精彩推荐