当用户在ComboBox(WPF)中选择特定项时,如何更改FontFamily

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (195)

textblock的FontFamily正确绑定到组合框; 但是当用户选择组合框(use default font)中的第一个项目时,如何将文本块字体更改为此?

FontFamily={StaticResource Great} 

App.xaml中:

<Application x:Class="WpfApp3.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <FontFamily x:Key="Great">/WpfApp3;component/#Great Times Font</FontFamily>
    </Application.Resources>
</Application>

MainWindow.xaml:

<Window x:Class="WpfApp3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        FontFamily="{StaticResource Great}"
        FontSize="18"
        xmlns:properties="clr-namespace:WpfApp3.Properties"
        FlowDirection="LeftToRight"
        mc:Ignorable="d"
        Title="MainWindow" Height="144.469" Width="436.876">

    <StackPanel VerticalAlignment="Center" 
                HorizontalAlignment="Center"  
                Width="250">
        <ComboBox
            Text="{Binding Source={x:Static properties:Settings.Default}, Path=Font, Mode=OneWay}"
            SelectedItem="{Binding Source={x:Static properties:Settings.Default}, Path=Font, Mode=TwoWay}">

            <ComboBox.ItemsSource>
                <CompositeCollection>
                    <ComboBoxItem Content="Use Default Font"/>
                    <CollectionContainer Collection="{Binding Source={x:Static Fonts.SystemFontFamilies}}"/>
                </CompositeCollection>
            </ComboBox.ItemsSource>
        </ComboBox>

        <TextBlock 
            Text="Text in selected font" 
            FontFamily="{Binding Source={x:Static properties:Settings.Default}, Path=Font, Mode=OneWay}"/>

    </StackPanel>
</Window>
提问于
用户回答回答于

如果您只想更改TextBlock的字体,请将其FontFamily属性直接绑定到ComboBox的SelectedItem:

    <ComboBox x:Name="theComboBox">

        <ComboBox.ItemsSource>
            <CompositeCollection>
                <ComboBoxItem Content="Use Default Font"/>
                <CollectionContainer Collection="{Binding Source={x:Static Fonts.SystemFontFamilies}}"/>
            </CompositeCollection>
        </ComboBox.ItemsSource>
    </ComboBox>

    <TextBlock Text="Text in selected font" FontFamily="{Binding ElementName=theComboBox, Path=SelectedItem}" />

如果要将设置应用于整个应用程序,请为父项设置FontFamily <Window>

如果您想要一些可以保存为设置的内容,那么您需要将两者绑定到视图模型中的属性,然后将其保存到设置中。

扫码关注云+社区

领取腾讯云代金券