user2505650
user2505650

Reputation: 1381

Detect what has been selected on a Listbox DataTemplate

I have a Listbox which is bonded to a list of an object that holds two elements : a string and an image

I want to detect if the user taps on the image or on the textblock

This is what I tried :

this is my xaml :

<ListBox x:name = "TheList"  ItemSource ="{Binding List}" SelectionChanged="SelectionChanged_1">
    <DataTemplate>
        <TextBlock Text = "{Binding Name}" />
        <Image ImageSource = "{Binding Picture}" />
        <StackPanel>
        <\StackPanel>
    <\DataTemplate>
</ListBox>

And here is my code behind :

private void SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
    if (TheList.SelectedItem != null)
    {
        if(e.OriginalSource == sender as  TextBox ){
             MessageBox.Show("Text");

        }  else if(e.OriginalSource  == sender as Image ){

            MessageBox.Show("Image");

        }
    }
}

But it does not work if i tap on the image the MessageBox shows "Text"

How can I detect if the image or the textblock has been tapped?

Upvotes: 1

Views: 284

Answers (3)

user2505650
user2505650

Reputation: 1381

I have finally found my answer :

I had to add this line :

var myTappedobject = (Sender as FrameworkElement).DataContext as MyObject

Upvotes: -1

Jaihind
Jaihind

Reputation: 2778

You can not achive on SelectionChanged event of ListBox Control. but You can do it in this way

<ListBox x:name = "TheList"  ItemSource ="{Binding List}" SelectionChanged="SelectionChanged_1">
   <DataTemplate>
     <TextBlock Text = "{Binding Name}" Tap="txtBlock_Tap" />
      <Image ImageSource = "{Binding Picture}" Tap="img_Tap"/>
      <StackPanel>
       <\StackPanel>
    <\DataTemplate>
</ListBox>

 private void txtBlock_Tap(object sender, System.Windows.Input.GestureEventArgs e)
    {
      MessageBox.Show("TextBlock click");
      var item = TheList.SelectedItem as your Type;
     }

 private void img_Tap(object sender, System.Windows.Input.GestureEventArgs e)
     {
       MessageBox.Show("Image click");
       var item = TheList.SelectedItem as your Type;
     }

Upvotes: 1

deeiip
deeiip

Reputation: 3379

you can try:

<ListBox x:name = "TheList"  ItemSource ="{Binding List}" SelectionChanged="SelectionChanged_1">
<DataTemplate>
    <TextBlock Click=hTClick" Text = "{Binding Name}" />
    <Image Click="hIClick" ImageSource = "{Binding Picture}" />
    <StackPanel>
    <\StackPanel>
<\DataTemplate>

In code behind:

private void hTClick(object sender, SelectionChangedEventArgs e)
{
    MessageBox.Show("text");
}
private void hIClick(object sender, SelectionChangedEventArgs e)
{
    MessageBox.Show("image");
}

This will show you what you want.

Upvotes: 1

Related Questions