Search code examples
c#uwpstackpanel

Retrieve object from tapped stackpanel element


As the title suggests, I am struggling with retrieving an element from a stackpanel list when tapping it in a simple UWP application. The stackpanel has its itemsource connected to a list of "Customers" which I am then displaying

            ObservableCollection<Customer> customers = new ObservableCollection<Customer>();
            // Create a new ListView (or GridView) for the UI, add content by setting ItemsSource
            ListView customersLV = new ListView();
            customersLV.ItemsSource = customers;

            // Add the ListView to a parent container in the visual tree (that you created in the corresponding XAML file)
            customerPanel.Children.Add(customersLV);

The XAML-code looks like this (Added a scrollviewer for longer lists):

        <ScrollViewer VerticalScrollBarVisibility="auto" HorizontalScrollBarVisibility="auto" Margin="63,341,1043,368" >
            <StackPanel x:Name="customerPanel" Height="441" Width="394" DoubleTapped="customerPanel_DoubleTapped" ></StackPanel>
        </ScrollViewer>

While adding and removing items from the list works great, I cannot seem to access any particular Customer-object from the listpanel when double tapping it. Here is my doubletap event function:

    private void customerPanel_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e)
    {
        testText.Text = e.OriginalSource.ToString();
    }

This seems to only print a reference to the whole stackpanel and not to the specific object that I double-tapped. How can I access the tapped Customer-object if I, for example, wanted to call its ToString-method?

Thank you for your time :)


Solution

  • Solved it now I think! I simply put a listView within my StackPanel like this.

    <ScrollViewer VerticalScrollBarVisibility="auto" HorizontalScrollBarVisibility="auto" Margin="63,341,1043,368" >
                <StackPanel x:Name="customerPanel" Height="441" Width="394">
                    <ListView x:Name="customersLV" Tapped="listView_Tapped">
                    </ListView>
                </StackPanel>
    </ScrollViewer>
    

    The CS code looked like this:

    ObservableCollection<Customer> customers;
    public MainPage()
    {
          this.InitializeComponent();
    
          customers = new ObservableCollection<Customer>();
    
          customersLV.ItemsSource = customers;
    }
    
    
    private void listView_Tapped(object sender, TappedRoutedEventArgs e)
    {
          testBox.Text = customersLV.SelectedItem.ToString();
    }
    

    This will print out the string representation of the actual Customer object in my testBox textblock :)