Event !
-
I have a list: List ImgRow1 = new List(); and i set: foreach (Image item in ImgRow1) { item.MouseDown += new MouseButtonEventHandler(item_MouseDown); } in private void item_MouseDown(object sender, MouseButtonEventArgs e) { } and i want to get index of sender (for example: ImgRow1[2] => index=2 ). Sorry for my english. Thank !
-
I have a list: List ImgRow1 = new List(); and i set: foreach (Image item in ImgRow1) { item.MouseDown += new MouseButtonEventHandler(item_MouseDown); } in private void item_MouseDown(object sender, MouseButtonEventArgs e) { } and i want to get index of sender (for example: ImgRow1[2] => index=2 ). Sorry for my english. Thank !
If ImgRow1 is a property like:
public List<Image> ImgRow1 { get; set; }
and is in scope in the event handler, then you can modify the event handler like this:
private void item_MouseDown(object sender, MouseButtonEventArgs e)
{
Image myImage = (Image)sender;
int index = ImgRow1.IndexOf(myImage);MessageBox.Show(index.ToString()); }
Or, You could create your own "IndexedImage" class with a ListIndex property, inheriting from Image and use that.
public class IndexedImage : Image
{
public int ListIndex { get; set; }public IndexedImage() { } }
When you add the event handler, add the list index as well:
foreach (IndexedImage item in ImgRow1)
{
item.MouseDown +=new MouseButtonEventHandler(item_MouseDown);
item.ListIndex = ImgRow1.IndexOf(item);
}Then in the event handler you can get the ListIndex property:
private void item_MouseDown(object sender, MouseButtonEventArgs e)
{
IndexedImage myImage = (IndexedImage)sender;
MessageBox.Show(myImage.ListIndex.ToString());
}but that has other issues, in that the index may change later on, so the class would need to be more complicated in reality.
modified on Sunday, October 11, 2009 4:51 PM