VB.net code for Stackpanel in WPF combobox

296 views Asked by At

I have an XAML as follows:

   <ComboBox x:Name="FruitcomboBox" HorizontalAlignment="Left" Margin="75,270,0,0" VerticalAlignment="Top" Width="220" Height="65" SelectedIndex="0">
            <ComboBoxItem>
                <StackPanel Orientation="Horizontal">
                    <Image Source="apple.jpg" Height="46" Width="43"></Image>
                    <TextBlock> Apple</TextBlock>
                </StackPanel>
            </ComboBoxItem>
            <ComboBoxItem>
                <StackPanel Orientation="Horizontal">
                    <Image Source="E:\Documents\User interface design\orange.jpg" Height="41" Width="48"></Image>
                    <TextBlock> Orange</TextBlock>
                </StackPanel>
            </ComboBoxItem>
            <ComboBoxItem>
                <StackPanel Orientation="Horizontal">
                    <Image Source="E:\Documents\User interface design\watermelon.jpg" Height="46" Width="53"></Image>
                    <TextBlock> Water Melon</TextBlock>
                </StackPanel>
            </ComboBoxItem>

        </ComboBox>

I would like to achieve the above via VB.net as I need to dynamically add stackpanels to the combobox.

I know how to add an item to the combobox via combobox.items.add but how do I add stackpanels and textblock?

Some code snippers will be helpful.

1

There are 1 answers

0
mm8 On BEST ANSWER

I know how to add an item to the combobox via combobox.items.add but how do I add stackpanels and textblock?

You create these dynamically and set the Content property of the ComboBoxItem to the StackPanel:

Dim sp As New StackPanel() With {.Orientation = Orientation.Horizontal}

Dim img As New Image() With {.Source = New BitmapImage(New Uri("pear.png", UriKind.RelativeOrAbsolute)), .Width = 43, .Height = 46}
sp.Children.Add(img)

Dim tb As New TextBlock With {.Text = "Pear"}
sp.Children.Add(tb)

Dim item As New ComboBoxItem With {.Content = sp}
FruitcomboBox.Items.Add(item)