Displaying FontFamily in Combobox

≡放荡痞女 提交于 2019-12-04 06:28:05

ItemsSource here expects a collection; e.g. Fonts.SystemFontFamilies

<ComboBox ItemsSource="{Binding Source={x:Static Fonts.SystemFontFamilies}}"/>

Actually, here's a very nice link covering font selection:

http://www.hanselman.com/blog/LearningWPFWithBabySmashCustomerFeedbackAndAWPFFontComboBox.aspx

Scott Hanselman even shows how to render each font item in combobox with it's own font family.


Added per OP comment.

Here's an example of binding to dependency property. Property is named "MyFontFamily" to avoid collision with existing Window's property. Sorry, no Ribbon controls (I have bare 3.5 sp1).

Window1.xaml

<Window
    x:Class="SimpleWpf.Window1"
    x:Name="ThisWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel Orientation="Vertical">
        <ComboBox
            SelectedItem="{Binding MyFontFamily, ElementName=ThisWindow}"
            ItemsSource="{Binding Source={x:Static Fonts.SystemFontFamilies}}"/>
        <TextBlock
            Text="Lazy dog jumper"
            FontFamily="{Binding MyFontFamily, ElementName=ThisWindow}"
            FontSize="24"/>
    </StackPanel>
</Window>

Window1.xaml.cs

public partial class Window1 : Window
{
    // ...

    public static readonly DependencyProperty MyFontFamilyProperty =
        DependencyProperty.Register("MyFontFamily",
        typeof(FontFamily), typeof(Window1), new UIPropertyMetadata(null));
}

A just in Xaml solution with fonts sorted in alphabetical order:

<Window x:Class="WpfFontsComboBox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:System="clr-namespace:System;assembly=mscorlib"
        xmlns:ComponentModel="clr-namespace:System.ComponentModel;assembly=WindowsBase"
        Height="350" Width="525">
    <Window.Resources>
        <CollectionViewSource x:Key="SortedFontsCollection" Source="{Binding Source={x:Static Fonts.SystemFontFamilies}}" >
            <CollectionViewSource.SortDescriptions>
                <ComponentModel:SortDescription PropertyName="Source" />
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>
    </Window.Resources>
    <StackPanel>
        <Label Content="42" FontFamily="{Binding ElementName=comboBoxFonts, Path=SelectedItem}" />
        <ComboBox x:Name="comboBoxFonts" ItemsSource="{Binding Source={StaticResource SortedFontsCollection}}" />
    </StackPanel>
</Window>

A great Font Combobox for WPF can be found here:

CodeProject.com: A XAML-Only Font ComboBox

It is pure XAML, can be just copied/pasted and even sorts the fonts properly. The article also describes nicely all the gotchas encountered and how to solve them.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!