rockydant
rockydant

Reputation: 129

Set value to FontDialog in WPF

I am working on WPF with text. Now I want to edit text using FontDialog but I cannot set current style of text to FontDialog so the style of text change everytime I call FontDialog. Can you guys help me?

This my code:

System.Windows.Forms.FontDialog fontDialog = new System.Windows.Forms.FontDialog();
        if (fontDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            this.textAnnotation.Font.Size = fontDialog.Font.Size;
            this.textAnnotation.Font.Name = fontDialog.Font.Name;
            this.textAnnotation.Font.Underline = fontDialog.Font.Underline;
            this.textAnnotation.Font.Strikeout = fontDialog.Font.Strikeout;
            this.textAnnotation.Font.Bold = fontDialog.Font.Bold;
            this.textAnnotation.Font.Italic = fontDialog.Font.Italic;
        }

Upvotes: 1

Views: 4973

Answers (2)

Rankit Dua
Rankit Dua

Reputation: 49

You can create a new Font object passing your current style of text as parameter. This is how you can do it :

        var fontDialog = new FontDialog();
        fontDialog.Font = new Font(textInfo.FontFamily, textInfo.FontSize);

        if (fontDialog.ShowDialog() == DialogResult.OK)
        {
            var selectedFont = fontDialog.Font;
            textInfo.FontSize = selectedFont.Size;
            textInfo.FontFamily = selectedFont.FontFamily.Name;
            textInfo.FontWeight = selectedFont.Bold ? "Bold" : "Regular";
            textInfo.FontStyle = selectedFont.Italic ? "Italic" : "Normal";            
        }            

Upvotes: 0

Mark Hall
Mark Hall

Reputation: 54562

The Font object in WPF is different than the Font object in Windows Forms which your FontDialog returns.

  1. The Fontsize will not error but WPF Font Sizes are different that WinForms.
  2. You will need to use a FontFamilyConverter to set the Font Name.
  3. The Underline and Strikeout are TextDecorations in WPF
  4. For Font Style and Font Weight propertys you can use conditional logic to set the properties.

You would be better off using something that is native to Wpf since the Font objects are different. There is a Sample Font Chooser on the Wpf Text blog. I would recommend looking into it.

something like this:

System.Windows.Forms.FontDialog fontDialog = new System.Windows.Forms.FontDialog();
if (fontDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    FontFamilyConverter ffc = new FontFamilyConverter();

    this.textAnnotation.FontSize = fontDialog.Font.Size;
    this.textAnnotation.FontFamily =(FontFamily)ffc.ConvertFromString(fontDialog.Font.Name);

    if (fontDialog.Font.Bold)
        textAnnotation.FontWeight = FontWeights.Bold;
    else
        textAnnotation.FontWeight = FontWeights.Normal;

    if (fontDialog.Font.Italic)
        textAnnotation.FontStyle = FontStyles.Italic;
    else
        textAnnotation.FontStyle = FontStyles.Normal;
}

Upvotes: 3

Related Questions