Search code examples
wpfdatatemplatelistitem

How to access ListItem from code behind when using DataTemplate - ListBox


I have listbox which binds data to DataTable and now I need to access specific List Item, let's say first 5th one, from source behind code:

<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>

Here is my foreach loop to access each listitem but I am enable to cast liSelectedMainCategory to ListItem...What am I doing wrong????

foreach (ListItem liSelectedMainCategory in lbMainCategores.Items)
                { }

Solution

  • You are using the Items property which is a collection of containers. Elements in that collection would not cast the way you want. Consider using something like this fragment...

        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...
            }
        }