为什么会出错? 我希望屏幕显示所选项目的内容(在此示例中.Text)
XAML:
<ListBox Name="Lbox" SelectionChanged="Lbox_SelectionChanged"
SelectionMode="Extended">
<TextBlock>AAA</TextBlock>
<TextBlock>BBB</TextBlock>
<TextBlock>CLabel</TextBlock>
</ListBox>
<Button Click="Button_Click">Click</Button>
代码:
private void Button_Click(object sender, RoutedEventArgs e)
{
StringBuilder str = new StringBuilder();
foreach (ListBoxItem item in Lbox.Items)
{
if (item.IsSelected)
{
TextBlock t = item as TextBlock; // Error, Can not cast. But why?
str.Append(t.Text + " ");
}
}
MessageBox.Show(str.ToString());
}
答案 0 :(得分:4)
您因ListBoxItem
is not a TextBlock
而收到错误。我相信您可以通过ListBoxItem
媒体资源访问Content
的内容。
您已经制作了ListBox的根元素TextBlocks。因此,当您遍历Lbox.Items
集合时,它们是TextBlocks
而不是ListBoxItems
。
相反,如果您将XAML更改为:
<ListBox Name="Lbox">
<ListBoxItem>Item1</ListBoxItem>
<ListBoxItem>Item2</ListBoxItem>
<ListBoxItem>Item3</ListBoxItem>
</ListBox>
然后这段代码就可以了:
private void Button_Click(object sender, RoutedEventArgs e)
{
var str = new StringBuilder();
foreach (ListBoxItem item in Lbox.Items)
{
if (item.IsSelected)
{
str.Append( item.Content + " ");
}
}
MessageBox.Show(str.ToString());
}
答案 1 :(得分:1)
试试这个:
private void Button_Click(object sender, RoutedEventArgs e)
{
StringBuilder str = new StringBuilder();
foreach (TextBlock item in Lbox.Items)
{
str.Append(item.Text + " ");
}
MessageBox.Show(str.ToString());
}