Domanda

I know there should be a simple solution to this question but I just cant seem to figure it out here is what my code looks like:

<ListBox HorizontalAlignment="Left"
         x:Name="locationsNB"
         VerticalAlignment="Top"
         Height="563"
         Width="455"
         SelectionChanged="locationsNB_SelectionChanged">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <StackPanel Orientation="Horizontal"
                  Margin="18,0,0,0"
                  x:Name="placeDetails">
        <Image Source="{Binding icon}"
               Height="40"
               Width="40"
               VerticalAlignment="Top"
               Margin="0,10,8,0" />
        <StackPanel Width="350">
          <TextBlock Text="{Binding name}"
                     FontSize="35"
                     Foreground="#399B81"
                     TextWrapping="Wrap" />
          <TextBlock Text="{Binding vicinity}"
                     FontSize="20"
                     Foreground="#888888"
                     TextWrapping="Wrap" />
          <TextBlock x:Name="reference"
                     Text="{Binding reference}"
                     Visibility="Collapsed" />
        </StackPanel>
      </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

I want to get the stackpanel->reference text (Text="{Binding reference}") of the selected item I dont know what my C# should look like but any help will be greatly appreciated.

È stato utile?

Soluzione

If the ItemsSource of your ListBox is bound to a collection of items then you can use the SelectedItem property of the ListBox

private void locationsNB_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var listbox = (ListBox)sender;

    var myObject = listbox.SelectedItem as MyCustomObject;
    if (myObject == null) return;

    // perform your custom logic with this item
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top