列表框选择

本文关键字:选择 列表 | 更新日期: 2023-09-27 18:21:28

为什么会出现错误?我想筛选出所选项目的内容(在这个例子中。文本)

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());
}

列表框选择

您收到错误是因为ListBoxItem不是TextBlock。我相信您可以通过Content属性访问ListBoxItem的内容。

您已经将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());
}

试试这个:

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());
}