简体   繁体   中英

C#, VS2010 - Changing font and other properties?

Creating a text editor just to try and hone my programming skills some more. I have the winform opening new text files, saving them and the usual undo, redo, copy, paste etc etc. However. I'm now trying to change the font.

When you click the "change font" button in the menu strip, a new form appears and loads all available fonts you can use into a list box.

List<string> fonts = new List<string>();

        foreach (FontFamily font in System.Drawing.FontFamily.Families)
        {
            fonts.Add(font.Name);
        }

        listboxfont.DataSource = fonts;

Now before I edit the text on the other page, I wanted to edit a sample label to test everything is okay!

After some research, I come across many bits of code like this..

lblsample.Font = new Font(listboxfont.SelectedItem, 12);

I might be wrong, but I see no reason why I can't use the selected item from the list box, which IS the fonts and use that to edit the label however it is giving me the error..

"Text_editor.font does not contain a constructor that takes 2 arguments.

Have tried and tried but no luck. Can anybody help?

It is because listboxfont.SelectedItem is an object . You need to cast it to a string so:

lblsample.Font = new Font((string)listboxfont.SelectedItem, 12);

or if you prefer:

lblsample.Font = new Font(listboxfont.SelectedItem.ToString(), 12);

That should do the trick!

UPDATE - Full example

Add listbox named listboxfont

Add label named lblsample

Add button named btnPreview

private void Form1_Load(object sender, EventArgs e)
{
    List<string> fonts = new List<string>();

    foreach (FontFamily font in System.Drawing.FontFamily.Families)
    {
        fonts.Add(font.Name);
    }
    listboxfont.DataSource = fonts;
}

private void btnPreview_Click(object sender, EventArgs e)
{
    lblsample.Font = new Font(listboxfont.SelectedItem.ToString(), 12);
}

You have declared a variable named font in your Text_editor form. (note the casing.. all lowercase!)

OR

The message you typed in your question has a typo. Is it Text_editor.fonts does not contain a constructor that takes 2 arguments. ? If yes, then you have used your fonts variable wrongly, which is not of Font type, but instead is of List<string> type.

Name your variables properly, and it should start working.

Try this:

lblsample.Font = new Font(listboxfont.SelectedItem.ToString(), 12.0f);

The Font constructor requests a String and a float

public Font(
string familyName,
float emSize
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM