列表框与列表同步吗?
我的 WinForms 上有一个列表框,用户可以在其中上下移动项目,该列表框与我的列表相同,我想知道保持两者同步的最有效方法是什么。
例如,要向下移动一个项目,我有:
int i = this.recoveryList.SelectedIndex;
object o = this.recoveryList.SelectedItem;
if (i < recoveryList.Items.Count - 1)
{
this.recoveryList.Items.RemoveAt(i);
this.recoveryList.Items.Insert(i + 1, o);
this.recoveryList.SelectedIndex = i + 1;
}
我有:
public List<RouteList> Recovery = new List<RouteList>();
我想根据列表框保持更新。
我应该简单地清除恢复并使用当前列表框数据进行更新,还是有更好的方法在上下移动时更新?
我主要是问因为从列表框到列表的类型不同。
I have a listbox on my WinForms where users can move the items up and down and that listbox is as well the same as a list I have and I was wondering what would be the most efficient way to maintain both synchronized.
for example to move an item down I have:
int i = this.recoveryList.SelectedIndex;
object o = this.recoveryList.SelectedItem;
if (i < recoveryList.Items.Count - 1)
{
this.recoveryList.Items.RemoveAt(i);
this.recoveryList.Items.Insert(i + 1, o);
this.recoveryList.SelectedIndex = i + 1;
}
And I have:
public List<RouteList> Recovery = new List<RouteList>();
Which I would like to maintain updated against the listbox.
Should I simple clear Recovery and update with the current listbox data or is there a better way to update both when move up and down ?
I am mainly asking because the types from the listbox to the list are different.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
.Net 为此类行为提供内置支持。为了使用它,您需要将恢复列表的类型更改为:
然后使用该 BindingList 作为控件中的数据源:
下面是一个使用 String 的 BindingList 的简单示例。我的表单上有两个列表框,当所选元素与列表中的第一个元素交换时,它们都保持同步:
.Net provides built-in support for this type of behavior. In order to use it, you need to change the type of your Recovery list to:
And then you use that BindingList as the DataSource in your controls:
Here's a simple example using a BindingList of String. I have two listBox's on the form, and they both stay in sync as the selected element gets swapped with the first element in the list:
正确的方法是更改底层对象,然后让 UI 控件对该更改做出反应。
为了使 ListBox 对对象集合(列表)中的更改做出反应,您需要使用 ObservableCollection。它就像集合的 INotifyPropertyChanged。
然后,您可以通过向上/向下操作更改集合,而不是 UI。
编辑
我并不是说要在集合的顶部添加一个观察者。我是说改变你的收藏类型。不要使用 List,使用 ObservableCollection。它的工作方式(很大程度上)相同,但会通知绑定的 UI 控件其项目的更改。
至于例子,请谷歌一下。无论如何,这就是我必须做的事情来提供一个..
The proper way is to change the underlying object and then have the UI Control react to that change.
For the ListBox to react to changes in your object collection (your List) you'd need to use an ObservableCollection instead. It's like the INotifyPropertyChanged for collections.
Then you make your up/down actions change the collection, NOT the UI.
EDIT
I am not saying to add an observer on TOP of the collection. I'm saying to change the type of your collection. Don't use List, use ObservableCollection. It works (largely) the same way but notifies the bound UI Controls of changes to it's items.
As for an example, please Google for it. That's what i'd have to do to provide one anyway..