I cannot change font size in C# (Property or indexer 'Font.Size' cannot be Assigned to -- it is read only)

Asked

Viewed 241 times

1

I did a Trackbar to change the font size in Visualstudio Express 2015,but when I try to change the font it returns the error "Property or indexer 'Font.Size' cannot be Assigned to -- it is read only" and I have no idea what to do. Code:

    private void FontTrackBar_Scroll(object sender, EventArgs e)
    {
        lblFontSize.Text = FontTrackBar.Value.ToString();       //seta o valor da barra numa label
        int FontSizeInt = FontTrackBar.Value;                   //Variavel com o valor da trackbar
        Form1.DefaultFont.Size = FontTrackBar.Value; //Aqui eu tento setar o tamanho da fonte e dá erro
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        FontTrackBar.Value = Convert.ToInt16(8);                //seta o padrão da fonte   
        lblFontSize.Text = FontTrackBar.Value.ToString();
    }

Edit: I fixed an error now but it’s still the same. Print do Codigo com o erro

2 answers

0

You will need to build another object Font. Also, you cannot change the property DefaultFont of some control, this is a static property used to fallback.

In this case, it is necessary to change the value of the instance property Font.

Font = new Font(DefaultFont.FontFamily, novoTamanho);

Working example:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        StartPosition = FormStartPosition.CenterScreen;
        Text = "Título";

        var button = new Button
        {
            Size = new Size(50, 30),
            Location = new Point(10, 10),
            Text = "Texto"
        };

        button.Click += ChangeFont;

        Controls.Add(button);

    }

    public void ChangeFont(object _, EventArgs __) 
        => Font = new Font(DefaultFont.FontFamily, Font.Size + 1);
}

inserir a descrição da imagem aqui

0


This property is read-only as stated in the error itself: Property or indexer 'Font.Size' cannot be assigned to -- it is read only if you want to change the font size of the form it has to be by the property box or then by the instance of its class, example:

Form1 frm = new Form1();
frm.Font = new Font("Arial", 12);

or if you are in the instance:

this.Font = new Font("Arial", 12);

in your code:

private void FontTrackBar_Scroll(object sender, EventArgs e)
{
    lblFontSize.Text = FontTrackBar.Value.ToString();
    int FontSizeInt = FontTrackBar.Value;
    this.Font = new Font(DefaultFont.FontFamily.Name, FontTrackBar.Value); // aqui
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.