我有一个包含填充TextBoxes的项目的ListBox。如何识别从ListBox中进行选择时选择的文本字符串。下面是我的ListBox的XAML代码
<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>我已经在我的selection_changed方法中尝试了所有的东西。这是最新的一条:
object selectedItem = ScenarioList.SelectedItem;
ListBoxItem selected = this.ScenarioList.ItemContainerGenerator.ContainerFromItem(this.ScenarioList.SelectedItem) as ListBoxItem;
string tempStr = selected.Content.ToString();发布于 2012-06-20 07:20:46
ListBoxItem listBox_Item = listBox.SelectedItem as ListBoxItem;
MessageBox.Show("You have selected " + listBox_Item.Content.ToString());或者您可以在Selection changed事件上尝试此选项
private void ScenarioList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (((ListBox)sender).SelectedItem != null)
MessageBox.Show("You have selected " + (ListBox)sender).SelectedItem);
}发布于 2012-06-20 07:31:16
你可以这样做:
var selectedText = ((TextBlock)((ListBoxItem)ScenarioList.SelectedItem).Content).Text你也可以从SelectionChangedEventArgs获取它,类似于:
public void ScenarioList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var item = e.AddedItems[0] as ListBoxItem;
var selectedText = ((TextBlock)item.Content).Text;
}https://stackoverflow.com/questions/11110778
复制相似问题