39

How do I set the font of a TextBox from a string in the code behind?

// example
txtEditor.FontFamily = "Consolas";
Usama Abdulrehman
  • 1,041
  • 3
  • 11
  • 21
Jiew Meng
  • 84,767
  • 185
  • 495
  • 805

6 Answers6

61
txtEditor.FontFamily = new FontFamily("Consolas"); // the Media namespace
Gishu
  • 134,492
  • 47
  • 225
  • 308
  • If `txtEditor` is a [System.Windows.Forms.TextBox](https://msdn.microsoft.com/en-us/library/system.windows.forms.textbox%28v=vs.110%29.aspx), there is no FontFamily property on that object, but there is a [Font](https://msdn.microsoft.com/en-us/library/system.windows.forms.control.font(v=vs.110).aspx) property. – Spencer Williams Jan 07 '16 at 18:46
20

Use the following syntax:

lblCounting.Font  = new Font("Times New Roman", 50);

Where lblCounting is just any label.

Nate
  • 30,286
  • 23
  • 113
  • 184
Furqan Ahmed
  • 201
  • 2
  • 2
  • Use the markdown and formatting tools to make your code display as code: `lblCounting.Font = new Font("Times New Roman", 50);` – nickhar Nov 08 '12 at 15:38
8
System.Drawing.Font = new Font("Arial", 8, FontStyle.Bold);
Adi Lester
  • 24,731
  • 12
  • 95
  • 110
Amir Nazari
  • 113
  • 1
  • 6
  • 1
    The question asked how to set the Font but the example implied the OP wanted to set the FontFamily. This answer answers the question if not the example and is the answer I was searching for (though I needed to correct it a bit.) – CramerTV Aug 09 '13 at 22:16
  • To be sure, the OP said nothing about FontFamily in the question, but you are right that it is in the example, but only for the TextBox, rather than setting the Font program-wide. – Spencer Williams Jan 07 '16 at 18:49
3

One simple way to do it globally, programmatically:

public MainWindow()
{
    this.FontFamily = new FontFamily("Segoe UI");
}
Strong84
  • 1,869
  • 2
  • 19
  • 24
3

Copy and paste your example code into the constructor of the form, right after InitializeComponent();

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        txtEditor.FontFamily = new FontFamily("Consolas");
    }
}
Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183
2

Use txtEditor.Font.Name = "Consolas";

Rahul Soni
  • 4,941
  • 3
  • 35
  • 58