VB.net WPF 组合框中 Stackpanel 的代码

VB.net code for Stackpanel in WPF combobox

我有一个XAML如下:

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

我想通过 VB.net 实现上述目标,因为我需要将堆栈面板动态添加到组合框。

我知道如何通过 combobox.items.add 将项目添加到组合框,但如何添加堆栈面板和文本块?

一些代码片段会有所帮助。

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

您动态创建这些并将 ComboBoxItem 的内容 属性 设置为 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)