如何为 WPF 中的每个组合框项目使用多种字体? [英] How to use multiple fonts for each combobox item in WPF?

查看:21
本文介绍了如何为 WPF 中的每个组合框项目使用多种字体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像这样在组合框中显示项目.

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)

解决方案

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:

这篇关于如何为 WPF 中的每个组合框项目使用多种字体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆