问题
hey guys im having a tough time trying to solve this problem ive been at for 3 hours and still couldn't find out why its doing this... here is the code
private void Catagory_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int selectedCategoryId = categoryIdList[categoryListBox.SelectedIndex];
client.GetItemsAsync(selectedCategoryId);
client.GetItemsCompleted +=
new EventHandler<GetItemsCompletedEventArgs>(client_GetItemsCompleted);
}
void client_GetItemsCompleted(object sender, GetItemsCompletedEventArgs e)
{
itemIdList.Clear();
itemNameList.Clear();
itemNumberList.Clear();
itemDisplayList.Clear(); //Clears the Display List Items
if (e.Error == null)
{
itemIdList = e.ItemIDList;
itemNumberList = e.itemNumber;
itemNameList = e.Result;
for (int i = 0; i < itemIdList.Count; i++)
{
itemDisplayList.Add(new ItemDisplay { itemNumber = itemNumberList[i], itemName = itemNameList[i] });
}
//Populating the listbox controll with the itemDisplaylist...
Items.ItemsSource = itemDisplayList;
}
else
{
MessageBox.Show("Problem in getting the items list.");
}
}
When i change the category the first time it works perfectly... by perfectly i mean that it calls the function GetItemsAsync(selectedCategoryId)
and grabs the results and calls the event handler client_GetItemsCompleted()
and the inner working of the event handler works as it is supposed to, it sets the lists with the proper data and displays the itemNumber and the itemName in the list box ... BUT when i change the category again to get different items it doesn't work properly, what it's doing is that it clears the lists and populates the lists as it is supposed to, runs the for loop and populates the listBox called Items
but for some reason it goes to the top of the function again and empties all the lists :/ ... please tell my why it's executing the function again .. and when i choose another category again it executes the event handler 3 times and then 4 times and so on .. anyone know why its doing this? i need this fixed for my project :(
回答1:
Everytime this is executed:
client.GetItemsCompleted +=
You add a subscriber to the event, so the second time it will fire twice (the third time triple times, etc..).
Either unsubscrice ( -= ) in the completed method:
void client_GetItemsCompleted(object sender, GetItemsCompletedEventArgs e)
{
try {
/* .... */
}
finally {
client.GetItemsCompleted -=
new EventHandler<GetItemsCompletedEventArgs>(client_GetItemsCompleted);
}
}
or initiate the client object before every call.
var client = new ...();
client.GetItemsAsync(selectedCategoryId);
client.GetItemsCompleted +=
new EventHandler<GetItemsCompletedEventArgs>(client_GetItemsCompleted);
来源:https://stackoverflow.com/questions/10768676/why-is-my-event-handler-firing-twice