Wpf 使用DataTemplate-ListBox时如何从代码隐藏中访问ListItem

Wpf 使用DataTemplate-ListBox时如何从代码隐藏中访问ListItem,wpf,datatemplate,listitem,Wpf,Datatemplate,Listitem,我有一个listbox,它将数据绑定到DataTable,现在我需要从源代码后面访问特定的列表项,比如说第一个第五个: <ListBox Grid.Column="1" ItemsSource="{Binding ElementName=_this, Path=AllMainCategoriesTable}" HorizontalAlignment="Center" BorderBrush="Transparent" Background="Transparent" x:Name="lbM

我有一个listbox,它将数据绑定到DataTable,现在我需要从源代码后面访问特定的列表项,比如说第一个第五个:

<ListBox Grid.Column="1" ItemsSource="{Binding ElementName=_this, Path=AllMainCategoriesTable}" HorizontalAlignment="Center" BorderBrush="Transparent" Background="Transparent" x:Name="lbMainCategories">
<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <RadioButton Grid.Column="0" Content="{Binding Path=main_category_name}" VerticalAlignment="Center" GroupName="grpMainCategory" x:Name="rdbEnableDisable" />
            <Label Grid.Column="1" Width="30" Background="Transparent" />
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

您正在使用Items属性,它是容器的集合。该集合中的元素不会按您想要的方式强制转换。考虑使用这样的片段…

    ICollectionView icv = CollectionViewSource.GetDefaultView(listBox1.Items);
    foreach (var v in icv)
    {
        var lbi = v as ListBoxItem;
        if (lbi != null)
        {
            var s = lbi.Content; // what you are after is here...
        }
    }

您正在使用Items属性,它是容器的集合。该集合中的元素不会按您想要的方式强制转换。考虑使用这样的片段…

    ICollectionView icv = CollectionViewSource.GetDefaultView(listBox1.Items);
    foreach (var v in icv)
    {
        var lbi = v as ListBoxItem;
        if (lbi != null)
        {
            var s = lbi.Content; // what you are after is here...
        }
    }

lbi始终为空:(如何获取ListBox DataTemplate中的access单选按钮?v是DataRowView,分配后lbi为空。它从不传递IF语句。我通过在单选按钮上添加Load事件来完成任务,并在单选按钮上检查这是否是所需的单选按钮,然后开始工作。但非常感谢您的帮助。lbi始终为空:(如何在ListBox DataTemplate中获取access单选按钮?v是DataRowView,分配后lbi为null。它从不传递IF语句。我通过在单选按钮上添加Load Event来完成任务,并在单选按钮上检查这是否是所需的单选按钮,然后开始工作。但非常感谢您的帮助。