用户在组合框(WPF)中选择特定项目时如何更改FontFamily

时间:2019-05-30 19:31:55

标签: c# wpf binding

enter image description here

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

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

我将文本块的fontfamily绑定到组合框中的所选字体。它可以正常工作。但是我希望当用户单击“使用默认字体” 时,文本块的fontfamily更改为:

FontFamily={StaticResource Great} //Great.ttf is an embedded font in my project

2 个答案:

答案 0 :(得分:0)

分配组合框的SelectionChanged事件以调用一种方法,在该方法中检查是否选中的项目是您想要的项目(yourItem),将文本块的FontFamily设置为您要的项目(YourFont)。

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

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

然后

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (theComboBox.SelectedItem = yourItem)
    {
        myTextBlock.FontFamily = YourFont;
    }
}

答案 1 :(得分:0)

您可以设置绑定的FallbackValue属性:

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