Reputation: 639
I have a Win Form C# app where I allow the user the set the font for a label. The default font is stored in a Properties.Settings entry for this app and selected using a Font Dialog.
In my app, I assign this font to a label:
Label.Font = Glob.ps.evFont; // Glob.ps is the Property.Settings for this app
For some reason, when I try to display this label, I get a "Parameter not valid" exception related to the font's "Height" property.
The fonts I've tried are pretty vanilla Windows fonts (Arial, Segoe UI etc). If I create the font explicitly in the label, the app works:
Label.Font = new Font("Arial", 12.0F, FontStyle.Bold);
Any ideas what's going on?
Upvotes: 0
Views: 543
Reputation: 426
The comment speaking on the Immutability of the Font attribute helped me to resolve my issue.
My solution is to construct a new Font object when setting that attribute, but construct it with the font family name and size of the font variable you have stored. This ensures that you don't get that annoying exception in the Height property.
Here is a snippet of my solution:
this.mainEditor.Font = new Font(Settings.Font.FontFamily.Name, Settings.Font.Size);
I store a font variable in my settings, but I only pull the attributes from it that are required to construct a new font model.
The problem was stated above in a comment. Basically the Font property is Immutable. So, you can store a Font object in a variable, but if you want to actually set the font property on an object, you have to do so by constructing a new Font object, you can't use an existing Font variable.
Upvotes: 0
Reputation: 1648
Is it possible the settings are being read correctly?
Created an empty winform project to test setting a font via the application settings and ended up with code a code behind like this, and it works fine.
Set a breakpoint and saw the label height property change (increase) after applying the font.
namespace WinForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Apply font from the properties settings
fontLabel.Font = WinForm.Properties.Settings.Default.evFont;
}
}
}
Upvotes: 1