WPF - Import custom fonts in C# - c#

I would like to import custom fonts on my WPF application so that they work without having the client to install them.
All the answers I have found so far are in XAML, I would like to do it only in C#.
My fonts are in Resources/Fonts/.
I have already tried this :
Fonts.GetFontFamilies(new Uri("pack://application:,,,/Resources/Fonts/#"));
But it didn't work.

I did everything bluetoothfx said but it still did not work.
Then I changed the Build action of my fonts (it was to Content), to Embedded Resource, and it worked. Resource works also for me.
Thanks anyway.

I think the way that you are working will not work.
At first create a folder name fonts then Add the font to your project, change its Build Action to Content.
Now you need to find the internal name (Real name) of the font not the font-file name. You can have it by opening the font file and you can see it on top.
Now edit App.xaml
<Application.resources>
<style x:key="MYFONT_INTERNAL_NAME">
<setter property="TextElement.FontFamily"
value="pack://application:,,,/fonts/#MYFONT_INTERNAL_NAME" />
</style>
Now use it in your code like:
<TextBlock Style="{StaticResource MYFONT_INTERNAL_NAME}" FontSize="16" Text="Font Style" />
To know more search here:
http://www.alteridem.net/2014/02/24/custom-fonts-in-wpf-applications/

Related

WPF font resouce not working, possible issue with font name

I am trying to use a font called Suisse Int'l Cond which is located in my project as fonts/SuisseIntlCond-Regular.otf and a build action of Resource
Other examples of OTF font in the project work without issue.
Works:
<Setter Property="FontFamily" Value="fonts/moon.otf #moon"/>
Dosn't Work:
<Setter Property="FontFamily" Value="fonts/SuisseIntlCond-Regular.otf #Suisse Int'l Cond"/>
My guess is it might be an issue with the ' char in the name or something wrong with the font itself but I have been unable to confirm either of these as the issue.
Importing and then exporting the font using Glyphr Studio resolves the issue even with keeping the same name.
How do I change a font's metadata (specifically a title)?

How do I dynamically change which Resource folder I get an image from?

I'm trying to implement 2 different themes for a WPF Application. I found this excellent post by #bendewey:
"Can WPF themes be used to include multiple skins for an application that can be changed at runtime?"
And have used it to implement two themes. I have created two Resource Folders, Lets call them ResourcesTheme1 and ResourcesTheme2 and Two Xaml Resource Dictionary files (Style1.xaml & Style2.xaml) that have the styles.
With this I have been able to set the following styles:
In Style1.xaml
<Style x:Key="HomeViewBackGroundImage" TargetType="Image">
<Setter Property="Source" Value="/ResourcesTheme1/Background.png" />
</Style>
In Style2.xaml
<Style x:Key="HomeViewBackGroundImage" TargetType="Image">
<Setter Property="Source" Value="/ResourcesTheme2/Background.png" />
</Style>
And this has worked a treat for me (if there's a better way please feel free to suggest it).
No the problem I have is that within my mainPage xaml I want to put on a row of buttons and each button has it's own image that it get's from binding to an ObservableCollection. I would like the Binding to look into the correct resource folder, but don't know how to make it happen without writing code behind.
So what I have is the following Binding:
<Image Name="ContentImage" Source="{Binding ImageName}" Stretch="UniformToFill">
And the following code behind:
if (useTheme1)
{
imageName = "/PlayingWithThemes;component/ResourcesTheme1/" + imageFileName;
}
else
{
imageName= "/PlayingWithThemes;component/ResourcesTheme2/" + imageFileName;
}
Any thoughts on how I could make the source for the image something like:
Source="ResourceFoler + {Binding ImageName}"
Or is there something more generic than:
/PlayingWithThemes;component/ResourcesTheme1/"
That I could use.
Thanks in advance.
A

Visual Studio Designer isn't displaying Embedded Font

I'm using some custom fonts in my C# WPF .NET 4.0 application (Open Sans and FontAwesome, specifically) with Visual Studio 2013.
I have:
Added FontAwesome.otf and OpenSans-Regular.ttf to my project (not as a link) under /Fonts.
Made sure both fonts are set to "Resource".
Installed both fonts locally (Windows 8.1).
Created new Styles in my Resource Dictionary (that contains many other pieces, so I'm confident it's working).
Restarted VS2013.
Here is a snippet of the Style I've created in my Resource Dictionary:
<Style x:Key="OpenSans">
<Setter Property="TextElement.FontFamily" Value="pack://application:,,,/Fonts/#Open Sans" />
</Style>
<Style x:Key="FontAwesome">
<Setter Property="TextElement.FontFamily" Value="pack://application:,,,/Fonts/#FontAwesome" />
</Style>
Now, in a new User Control I created purely to test the Designer and these fonts being included properly, I have written the following XAML:
<TextBlock Style="{StaticResource FontAwesome}" FontSize="64" Text="" />
<TextBlock Style="{StaticResource OpenSans}" FontSize="48" Text="the quick brown fox jumped over the lazy dog." />
<TextBlock FontFamily="Open Sans" FontSize="48" Text="the quick brown fox jumped over the lazy dog." />
FontAwesome works in the designer and when run, on both my PC and another PC without FoneAwesome installed.
The OpenSans Style does not display in the designer, but does when executed, including on another PC without Open Sans installed.
The Open Sans FontFamily selection displays in the designer, but does not display on another PC without Open Sans installed (expected).
Problem
I want to be able to use the Designer to see in design-time what the UI looks like given the provided Fonts I'm using. Leveraging the Styles I've created, I'm able to see the FontAwesome icons in the Designer, but not the Open Sans font. The only difference I can tell between the two is that FontAwesome is an Open-Type Font, whereas Open Sans is an True-Type Font.
Does anyone have an idea if I've overlooked something simple, or perhaps if there are obscure issues between OTF and TTF in the VS Designer?
Discoveries & Solution
I cannot discern why Open Sans is not rendering in the VS Designer. Every attempt I've made to coerce it to use Open Sans (from the font resource attached to the project) will fail, and the Designer falls back to the default font.
Using the same methods with FontAwesome works as expected, so there is some element to the font rendering system within VS that I can't explain.
However, I have come up a good (perhaps even better?) solution, and a tip that I didn't know about font selection in WPF:
The FontFamily Property in WPF supports fallback values, e.g.:
<Style x:Key="OpenSans">
<Setter Property="TextElement.FontFamily" Value="Open Sans, /<project name>;component/Fonts/#Open Sans" />
</Style>
Notice that the Value of this Property is firstly "Open Sans", and then following a comma, the URI to the font that's included in the project. (As a reminder, you need to be sure the font resource is of type "Resource" under Build Action Properties (Right-click on the Font file within the Solution Explorer.))
This syntax informs WPF to use the first font listed, and if not available, to then fallback to the second font family, and so forth on down the line.
This is (potentially) a better solution, as it asks the system if the desired font (in this example, Open Sans) is already available. If so, it uses that system font, and if not, it will load the embedded font file resource.
This provides a few benefits:
This setup causes the VS Designer to display fonts using Open Sans (in this example) where I use them, so I can design and see the font in question.
This setup also allows machines with the fonts being used to be loaded from the system first, and if not found, then load from the resource. Perhaps a minor performance-minded item, but still beneficial.
I hope this is beneficial to others who use Open Sans (or other fonts) that for some reason will not show up in the VS Designer unless referenced directly as a system font.

How to include external font in WPF application without installing it

How to include external font in WPF application without installing it
I tried this code
System.Drawing.Text.PrivateFontCollection privateFonts = new System.Drawing.Text.PrivateFontCollection();
privateFonts.AddFontFile("C:\\Documents and Settings\\somefont.ttf");
System.Drawing.Font font = new Font(privateFonts.Families[0], 12);
this.label1.Font = font;
It working correctly in Windows Form Application but not in WPF.
There are two ways of doing this: One way is to package the fonts inside the application. The other way is to have the fonts in a folder. The difference is mostly the URI you need to load the files with.
Package with Application
Add a /Fonts folder to your solution.
Add the True Type Fonts (*.ttf) files to that folder
Include the files to the project
Select the fonts and add them to the solution
Set BuildAction: Resource and Copy To Output Directory: Do not copy. Your .csproj file should now have a section like this one:
<ItemGroup>
<Resource Include="Fonts\NotoSans-Bold.ttf" />
<Resource Include="Fonts\NotoSans-BoldItalic.ttf" />
<Resource Include="Fonts\NotoSans-Italic.ttf" />
<Resource Include="Fonts\NotoSans-Regular.ttf" />
<Resource Include="Fonts\NotoSansSymbols-Regular.ttf" />
</ItemGroup>
In App.xaml add <FontFamily> resources. It should look like in the following code sample. Note that the URI doesn't contain the filename when packing with the application.
<Applicaton ...>
<Application.Resources>
<FontFamily x:Key="NotoSans">pack://application:,,,/Fonts/#Noto Sans</FontFamily>
<FontFamily x:Key="NotoSansSymbols">pack://application:,,,/Fonts/#Noto Sans Symbols</FontFamily>
</Application.Resources>
</Application>
Apply your fonts like this:
<TextBlock x:Name="myTextBlock" Text="foobar" FontFamily="{StaticResource NotoSans}"
FontSize="10.0" FontStyle="Normal" FontWeight="Regular" />
You can also set the font imperatively:
myTextBlock.FontFamily = new FontFamily(new Uri("pack://application:,,,/"), "./Fonts/#Noto Sans");
Copy to Output Directory
Add a /Fonts folder to your solution.
Add the True Type Fonts (*.ttf) files to that order
Include the files to the project
Select the fonts and add them to the solution
Set BuildAction: Content and Copy To Output Directory: Copy if newer or Copy always. Your .csproj file should now have a section like this one:
<ItemGroup>
<Content Include="Fonts\NotoSans-Bold.ttf">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="Fonts\NotoSans-BoldItalic.ttf">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="Fonts\NotoSans-Italic.ttf">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="Fonts\NotoSans-Regular.ttf">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="Fonts\NotoSansSymbols-Regular.ttf">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
In App.xaml add <FontFamily> resources. It should look like in the following code sample.
<Applicaton ...>
<Application.Resources>
<FontFamily x:Key="NotoSansRegular">./Fonts/NotoSans-Regular.ttf#Noto Sans</FontFamily>
<FontFamily x:Key="NotoSansItalic">./Fonts/NotoSans-Italic.ttf#Noto Sans</FontFamily>
<FontFamily x:Key="NotoSansBold">./Fonts/NotoSans-Bold.ttf#Noto Sans</FontFamily>
<FontFamily x:Key="NotoSansBoldItalic">./Fonts/NotoSans-BoldItalic.ttf#Noto Sans</FontFamily>
<FontFamily x:Key="NotoSansSymbols">./Fonts/NotoSans-Regular.ttf#Noto Sans Symbols</FontFamily>
</Application.Resources>
</Application>
Apply your fonts like this:
<TextBlock Text="foobar" FontFamily="{StaticResource NotoSansRegular}"
FontSize="10.0" FontStyle="Normal" FontWeight="Regular" />
References
MSDN: Packaging Fonts with Applications
I use such XAML code:
<Style x:Key="Hatten">
<Setter Property="TextElement.FontFamily" Value="Resources/#HATTEN" />
</Style>
#HATTEN - reference to hatten.tft in Resources.
Using the Style:
<TextBlock x:Name="lblTitle" Style="{DynamicResource Hatten}" FontSize="72"></TextBlock>
The best answer to this question I found here
http://geekswithblogs.net/Martinez/archive/2010/01/29/custom-font-in-wpf-application.aspx
SOLUTION
It involves using even more wicked string than before but works as expected:
<Label FontFamily="pack://application:,,,/Folder1/#Katana Sans">Text</Label>
Where is Folder1 is a folder of your project where you keep a TTF file.
Three notes at the end:
‘Katana Sans’ is the name of the font, not the name of the file. This is significant difference. To get the name of the font simply click the file twice. Note that spaces are included without any changes in this string.
Remember to put the hash sign ‘#’ in front of font name. It will not work otherwise.
Custom font may also be added to the project with ‘Build Action’ set to ‘Content’. This is not recommended approach however and for the sake of simplicity I ignored this possibility.
Some extra links
https://msdn.microsoft.com/en-us/library/ms753303(v=vs.100).aspx
https://msdn.microsoft.com/en-us/library/cc296385.aspx
The easiest way to include external fonts is to
Step 1. Create the folder Fonts And add your fonts into it.
Step 2. Set Build action to content and Copy to Output Directory to Copy always.
Step 3. Build the Solution to update it with the Font directory.
Step 4. Use the font in your elements using FontFamily="Fonts/#font name"
All Done!
Thanks to cscience !
I did not found any answer for exactly that.
But I found a solution that I did not saw on Internet.
I followed a recommendation of doing a folder and marking all the files inside as Resources.
But I needed to enumerate them, and that was my main problem, because I need to load all to my screen without recording the name somewhere. I just want to simple drop another font to that folder and list it.
I found this as a solution to list all the files inside my resources/fonts folder
Fonts.GetFontFamilies(new Uri("pack://application:,,,/resources/fonts/#"))
I expect it to help you organize your fonts.
I use xaml for this
<Window
FontFamily ="./Fonts/#somefont"
>
I included the font file inside the "Fonts" folder
First) Copy fonts to project folder like /Resources/Fonts/ and set font-properties -> Build Action:Resource
Second) Used on code
FontFamily="/AssemblyNamespace;component/Resources/Fonts/IranSans/#IRANSansWeb Medium"
Although the solution from #movgp0 worked at first, it failed when I wanted a Bold text. By searching a bit more online I found the following solution that works in all cases:
<Application.Resources>
<FontFamily x:Key="FiraSansBold">Fonts/FiraSansCondensed-Bold.ttf#Fira Sans Condensed</FontFamily>
<FontFamily x:Key="FiraSansBoldItalic">Fonts/FiraSansCondensed-BoldItalic.ttf#Fira Sans Condensed</FontFamily>
<FontFamily x:Key="FiraSansItalic">Fonts/FiraSansCondensed-Italic.ttf#Fira Sans Condensed</FontFamily>
<FontFamily x:Key="FiraSans">Fonts/FiraSansCondensed-Regular.ttf#Fira Sans Condensed</FontFamily>
</Application.Resources>
Usage: <Label FontFamily="{StaticResource FiraSansBold}">SomeBoldedLabel</Label>
I have a fonts folder inside an assets folder in my project. At build time it will copy those fonts into the folder as content. Then I can simply use the following XAML to use the FontAwesome font to have an icon on my button.
<Button Content="" FontFamily="./assets/fonts/#FontAwesome">
Here's What Worked for me:
(1) Add Directory to project: font
(2) Move ttf font file into font directory
(3) Add ttf font file to project
(4) Set the "Build" Property of the tff font file to "Resource"
(Note: I used "Resource" instead of "Embedded Resource"
in the combobox selection.)
(5) Open the Window where you are using the font and make the
following changes:
<Window ... >
<Window.Resources>
<FontFamily x:Key="YourFontNickName">
pack://application:,,,/font/#NameOfFont
<!-- Note: NameOfFont can be font by double clicking
on font from explorer and writing down name
of the font reported. Its not the same
as the file name -->
</FontFamily>
</Window.Resources>
<!-- Use font as Xaml -->
<StackPanel>
<Textblock FontFamily="{StaticResource YourFontNickName}">
This is a test
</Testblock>
<Textblock Name="text1"/>
</StackPanel>
...
</Window>
(6) If you want to change the font from code. Do this:
public partial class Window1 : Window {
// Use font as C# Code
public void UpdateText1() {
text1.Text = "Hi There";
FontFamily ff = this.Resources["YourFontNickName"]
as FontFamily;
if (ff == null) {
Messagebox.Show("Wrong Font Name", "ERROR");
return;
}
text1.FontFamily = ff;
text1.FontSize = 30;
}
...
}
You need to add fonts as resource item
according to the link; you may add your desired font as application resource file by following these steps:
copy your font file to anywhere in your project in most cases resource files is copied into a folder named "resources" if you want to follow this, create new folder in your project and name it as "resources" then copy your font file which is usually have ttf or otf format into that folder
then you need to declare this file as a resource file for doing so you have two options:
right click on your font file, select properties (or press F4 after selecting it)
and then change "Build Action" to "Resource"
go into your projects directory edit project-name.csproj file and the
following tag:
<ItemGroup>
<Resource Include="resources\<font-file-name>.ttf" />
</ItemGroup>```
finally within you application you may set font-family property like this:
FontFamily="./Resources/Fonts/#<font-name>"
be careful 'font-name' is different from font-file-name you may open font file and check for font name property (in Microsoft Window)
I was trying to get this to work as well with a different font,
it only worked for me in this format with the ./Fonts
<FontFamily x:Key="NotoSans">pack://application:,,,./Fonts/#Noto Sans</FontFamily>
Kind of, Really easy:
<TextBlock x:Name="lblTitle" FontSize="24" Margin="256,25,178,289" Text="gg" FontFamily="/FontTest;component/#Arvo"></TextBlock>
When you import a font, vs will gonna include it in font list😊.

Build Custom Theme or Use Standard Theme in WPF

Soon to be a professional .NET developer (I hope) I start to dig into Windows Presentation Foundation (WPF). Looking into several video tutorials, I find design of GUI a daunting task. Having to specify every color, on every element, in every situation, to every platform seems a bit too much. How can you make this process simpler, and more generic when it comes to design? Is there any templates to start from, or is one expected to specify a couple of hundred rows of XAML before the design is looking appealing?
Considering the code-block below...
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="LightGreen" />
<Setter Property="Foreground" Value="DarkGreen" />
</Style>
... where properties for hover and pushed-button style is left out which need additional rows of XAML to do what the developer wants.
Might there be a simple XAML-editor around to increase productivity? If there isn't, its just to dig dip into XAML and start building styles too keep for later projects.
Designing your own theme is great but it requires a lot of expertise and time. From my point of view its not a great idea to invest in designing your own theme, provided you already have so many themes availabe online. You can take one which suits you and modify it as per your needs.
I genrally refer these links for themes -
WPF Themes -
http://wpfthemes.codeplex.com/
http://wpf.codeplex.com/wikipage?title=WPF%20Themes&ProjectName=wpf
WPF Theme Selector
http://wpfthemeselector.codeplex.com/
Wpf Project With 21 Theme
https://marketplace.visualstudio.com/items?itemName=AliAlikhani.SahaWpfTheme2012
In case you need more options you can buy one here -
http://www.xamltemplates.net/wpf-themes/
There is no requirement to create a Style. You can just use the default style. Consider this simple messagebox style window:
<Window x:Class="MyProject.Test"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Test" Height="217" Width="298">
<StackPanel Orientation="Vertical">
<Label>Here is the Message.</Label>
<StackPanel Orientation="Horizontal">
<Button>OK</Button>
<Button>Cancel</Button>
</StackPanel>
</StackPanel>
</Window>
If you really need to re-style controls, I would pick and choose which ones to do. Otherwise, yes I think creating a custom style is a pretty big task.
Creating a custom style is a very large task, however, should you decide this is neccesary (it's not required). You can use Expression Blend to speed up the process.
Reuxables have a couple of free themes you can try. We've just bought one of their non-free ones and it's dead easy, you just throw in a reference in your app.xaml and it transforms your app. Easy to tailor, too.

Categories