Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to show items in combo box like this.

As shown in this image per item.

Is it possible? You can answer me in both c# or vb (for WPF)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
359 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can implement this easily by using data binding with item template inside comboBox as following:

First of all you need to create item template for your ComboBox, which can be done in many ways, Iam going to use the simplest way as following:

<ComboBox Width="200" Height="35" VerticalContentAlignment="Center" ItemsSource="{Binding Items}">
        <ComboBox.ItemTemplate>
            <DataTemplate DataType="{x:Type local:ItemViewModel}">
                <StackPanel Orientation="Horizontal">
                    <StackPanel.Resources>
                        <Style TargetType="TextBlock">
                            <Setter Property="FontSize" Value="12"></Setter>
                            <Setter Property="VerticalAlignment" Value="Center"></Setter>
                        </Style>
                    </StackPanel.Resources>
                    <TextBlock Text="{Binding HintText}"></TextBlock>
                    <TextBlock>
                        <Run>( </Run>
                        <Run FontFamily="{Binding HintFontFamily}" Text="{Binding HintText}"></Run>
                        <Run> )</Run>
                    </TextBlock>
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

Then I am going to create the view Model for ComboBox item and assign the DataContext for the main window to make the binding works correctly

Item view Model:

public class ItemViewModel
{
    public string Name { get; set; }
    public string HintText { get; set; }
    public string HintFontFamily { get; set; }
}

Main window (or your view) code:

public partial class MainWindow : Window
{
    public ICollection<ItemViewModel> Items { get; set; }

    public MainWindow()
    {
        Items = new List<ItemViewModel>()
        {
            new ItemViewModel()
            {
                Name="First element",
                HintText="First font",
                HintFontFamily="Lucida Handwriting"
            },
            new ItemViewModel(){
               Name="Second element",
                HintText="Second font",
                HintFontFamily="Track"
            }
        };
        //set the datacontext which is the binding source
        DataContext = this;
    }
}

Finally the result you get: Final result


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...