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 updat开发者_运维知识库ed 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.
.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:
public BindingList<RouteList> Recovery = new BindingList<RouteList>();
And then you use that BindingList as the DataSource in your controls:
listBox1.DataSource = Recovery;
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:
public partial class Form1 : Form
{
private readonly BindingList<string> list = new BindingList<string> { "apple", "pear", "grape", "taco", "screwdriver" };
public Form1()
{
InitializeComponent();
listBox1.DataSource = list;
listBox2.DataSource = list;
}
private void listBox1_KeyUp(object sender, KeyEventArgs e)
{
var tmp = list[0];
list[0] = list[listBox1.SelectedIndex];
list[listBox1.SelectedIndex] = tmp;
}
}
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..
精彩评论