在WPF應用程序中使用Font Awesome圖標


Font Awesome 在網站開發中,經常用到。今天介紹如何在WPF應用程序中使用Font Awesome 。

如果是自定義的圖標字體,使用方法相同。

下載圖標字體

  1. 在官方網站或github上下載資源

    http://fontawesome.io/#modal-download

    https://github.com/FortAwesome/Font-Awesome

  2. 解壓下載的文件(我是在github上下載的源碼),我們要使用的是其中css和fonts文件夾中的內容

    img

在項目中加入字體

  • 新建WPF應用,並新建存放字體的文件夾;

img

  • 把下載的fonts文件夾中的fontawesome-webfont.ttf復制到項目中存放字體的文件夾中,並設置其生成操作為Resource(默認即是);

img

  • 新建資源文件,存放所有圖標相關的資源;

img

  • 加入字體樣式;

首先加入字體的資源

<FontFamily x:Key="IconFont">/IconFontSample;component/fonts/fontawesome-webfont.ttf#Fontawesome</FontFamily>

然后加入樣式

  <Style x:Key="IconStyle" >
      <Setter Property="TextElement.FontFamily" Value="{StaticResource IconFont}" />
      <Setter Property="Control.OverridesDefaultStyle" Value="True"></Setter>
      <Setter Property="Control.UseLayoutRounding" Value="True"></Setter>
      <Setter Property="Control.SnapsToDevicePixels" Value="True"></Setter>
      <Setter Property="TextBlock.TextAlignment" Value="Center"></Setter>
      <Setter Property="TextBlock.VerticalAlignment" Value="Center"></Setter>
      <Setter Property="TextElement.FontSize" Value="12"></Setter>
  </Style>

處理圖標資源名稱

現在,我們需要把字體以WPF資源的形式加進來, 我們需要把CSS中

img

處理成

    <system:String x:Key="icon-glass">&#xf00c;</system:String>

處理的辦法其實還比多,比如可以寫個腳本什么的。 我這里介紹直接使用替換的方法

  • 在VS里打開font-awesome.css文件。(在下載的css文件夾中)

  • 把除下面這種格式的其它CSS樣式刪掉

    .fa-glass:before {
     content: "\f000";
    }
    
  • 使用<system:String x:Key="替換 .

  • 使用"> 替換:before {

  • 使用&#x 替換content: "\

  • 使用; 替換";

  • 使用</system:String> 替換}

  • 在資源文件中加入 xmlns:system="clr-namespace:System;assembly=mscorlib"

img

  • 把替換后的內容復制到資源文件中,處理報錯的行

img

如圖中,刪掉2000和2001行

使用

完成上面的操作后,我們就可以在應用程序中使用了。

  • 在App.xaml文件中,引入資源

    <Application.Resources>
           <ResourceDictionary>
               <ResourceDictionary.MergedDictionaries>
                  <ResourceDictionary Source="/IconFontSample;component/fonts/IconFontDictionary.xaml"></ResourceDictionary>
               </ResourceDictionary.MergedDictionaries>
           </ResourceDictionary>
      </Application.Resources>
    
    
  • 在應用程序中,就可以用使用資源的方式使用了

         <TextBlock Style="{DynamicResource IconStyle}" FontSize="26" 
                     Text="{DynamicResource fa-recycle}" Foreground="Brown"></TextBlock>
    

    可以通過設置fontsize和foreground來設置圖標的大小和顏色

    img


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM