Reputation: 1395
I have a ListBox
with items that fill TextBox
es. How do I identify the text string that is selected when a selection is made from the ListBox
. Here's my XAML code for the ListBox
:
<StackPanel x:Name="InputPanel" Orientation="Horizontal" HorizontalAlignment="Left">
<StackPanel>
<TextBlock Text="Input" Style="{StaticResource H2Style}"/>
<TextBlock Text="Select Scenario:" Style="{StaticResource H3Style}"/>
<ListBox x:Name="ScenarioList" Margin="0,0,20,0" HorizontalAlignment="Left" SelectionChanged="ScenarioList_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBoxItem x:Name="Scenario1">
<TextBlock Style="{StaticResource ListBoxTextStyle}" Text="1) Pick a single photo" />
</ListBoxItem>
<ListBoxItem x:Name="Scenario2">
<TextBlock Style="{StaticResource ListBoxTextStyle}" Text="2) Pick multiple files" />
</ListBoxItem>
<ListBoxItem x:Name="Scenario3">
<TextBlock Style="{StaticResource ListBoxTextStyle}" Text="3) Pick a folder" />
</ListBoxItem>
<ListBoxItem x:Name="Scenario4">
<TextBlock Style="{StaticResource ListBoxTextStyle}" Text="4) Save a file" />
</ListBoxItem>
</ListBox>
</StackPanel>
I have tried all kinds of things in my selection_changed
method. Here's the latest one:
object selectedItem = ScenarioList.SelectedItem;
ListBoxItem selected = this.ScenarioList.ItemContainerGenerator.ContainerFromItem(this.ScenarioList.SelectedItem) as ListBoxItem;
string tempStr = selected.Content.ToString();
Upvotes: 3
Views: 5065
Reputation: 3721
ListBoxItem listBox_Item = listBox.SelectedItem as ListBoxItem;
MessageBox.Show("You have selected " + listBox_Item.Content.ToString());
or You can try this one on Selection changed event
private void ScenarioList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (((ListBox)sender).SelectedItem != null)
MessageBox.Show("You have selected " + (ListBox)sender).SelectedItem);
}
Upvotes: 2
Reputation: 1090
You could do it like this:
var selectedText = ((TextBlock)((ListBoxItem)ScenarioList.SelectedItem).Content).Text
You can also get at it from SelectionChangedEventArgs something like:
public void ScenarioList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var item = e.AddedItems[0] as ListBoxItem;
var selectedText = ((TextBlock)item.Content).Text;
}
Upvotes: 2