Home > Mobile >  Handling a ComboBox inside a ListBox at runtime (XAML, WPF, C#)
Handling a ComboBox inside a ListBox at runtime (XAML, WPF, C#)

Time:10-06

I have a Listbox with several items. They are being added dynamically at runtime.

Each of these items has a Combobox with the same number of items, that should also be added at runtime.

<ListBox x:Name="ListBox_Parcels" 
                 ItemsSource="{Binding}"
                 SelectionMode="Multiple"
                 SelectionChanged="ListBox_Parcels_SelectionChanged">
           <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid Background="Transparent" Cursor="Hand">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>
                        <TextBlock x:Name="tb_title"
                                    Grid.Column="0" 
                                    Text="{Binding Name}" />
                        <ComboBox x:Name="Combobox_ParcelPreset"
                                  Grid.Column="1"
                                  SelectionChanged="ComboBox_ParcelPreset_SelectionChanged">
                            <ComboBoxItem Content="initItem1"/>
                            <ComboBoxItem Content="initItem2"/>
                        </ComboBox>
                    </Grid>
            </DataTemplate>
      </ListBox.ItemTemplate>
</ListBox>

Now I want to add an Item (yia background code at runtime) to all the ComboBox_ParcelPreset that are inside the listbox. I want to be able to set the selected index of a specific ComboBox inside the listbox and when the selection of the Combobox changed by the user to get the index both of the combobox and the listbox.

My problem is, that ComboBox_ParcelPreset does not exist, and ListBox_Parcels does not have any way to access the ComboBox.

        Itemlist_Parcels = new ObservableCollection<ClParcelItem>();
        ListBox_Parcels.DataContext = Itemlist_Parcels;

And if i change the selection in the combobox, i also do not get the index of the listbox.

Any hints welcome.

CodePudding user response:

What helped me was: How to access a specific item in a Listbox with DataTemplate?

for (int i = 0; i< ListBox_Parcels.Items.Count; i  )
            {
                ListBoxItem lbi = (ListBoxItem)ListBox_Parcels.ItemContainerGenerator.ContainerFromIndex(i);
                ComboBox cb = FindDescendant<ComboBox>(lbi);   
                cb.Items.Add(preset[0]);
                editing_parcel = (ClParcelItem)ListBox_Parcels.Items[i];
                if (ParcelNames.Exists(n => n == editing_parcel.Name))
                {
                    cb.SelectedIndex = cb.Items.Count - 1;
                }

            }
  • Related