Click here to Skip to main content
15,888,590 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a collection of classes that hold images and the paths of those images:

C#
public ObservableCollection<Item> PictureList { get; set; }

public class Item
{

public ImageSource picture { get; set; }
public string fullName { get; set; }

}


I am using a listbox to display the images.

<ListBox Height="Auto"
            Width="200"
                 Margin="0"
                 ItemsSource="{Binding PictureList}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>

                    <Image Source="{Binding picture}"
                           Height="100"
                           Width="100"
                           MouseUp="Picture_Click"/>

                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>


What I would like to be able to do is reference the fullName property in the Picture_Click event, however as the image is bound to picture I cannot figure out how to access the fullName property.

I have googled but had not luck in working this out.

Any help on this much appreciated.
Posted

You don't need the Button, just reference the DataContext of the Image similar to what you did:
C#
private void Picture_Click(object sender, RoutedEventArgs e)
{
  MessageBox.Show(((Item)(((Image)sender).DataContext)).fullName);
}

Ought to work.
 
Share this answer
 
Comments
GuyThiebaut 16-Oct-13 16:38pm    
Thanks Matt,

That does work - my code above was testing code so hopefully I can use what you have shown in the changes I have made.
I fixed it by wrapping the image inside a button:

HTML
<listbox height="Auto">
            Width="200"
                 Margin="0"
                 ItemsSource="{Binding PictureList}">
        <listbox.itemtemplate>
            <datatemplate>
                <stackpanel>

                    <button background="Transparent">
                            Click="Button_Click">
                        <image source="{Binding picture}">
                                   Height="100"
                                   Width="100"/>
                    </image></button>

                </stackpanel>
            </datatemplate>
        </listbox.itemtemplate>
    </listbox>

WIthin the Button_Click method I then reference the fullName property.

C#
private void Button_Click(object sender, RoutedEventArgs e)
      {

          MessageBox.Show(((Item)(((Button)sender).DataContext)).fullName);

      }


It's not pretty so anyone with a more elegant solution please post it here - thanks.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900