使用ComboBox C#更改RichBoxText字体

时间:2017-09-26 19:56:20

标签: c# winforms combobox

所以,我有这个代码似乎不起作用,我正在尝试使用ComboBox更改RichBoxText,只有 SelectedItems 似乎正在工作(来自 form1_load )。我是编程的初学者,所以请放轻松我。

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;

    namespace FormatarTexto
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void Form1_Load(object sender, EventArgs e)
            {
                comboBoxTipo.Items.Add("Arial");
                comboBoxTipo.Items.Add("Times New Roman");
                comboBoxTipo.Items.Add("Verdana");


                comboBoxEstilo.Items.Add("Normal");
                comboBoxEstilo.Items.Add("Negrito");
                comboBoxEstilo.Items.Add("Itálico");
                comboBoxEstilo.Items.Add("Sublinhado");

                comboBoxTamanho.Items.Add("10");
                comboBoxTamanho.Items.Add("12");
                comboBoxTamanho.Items.Add("14")


                comboBoxTipo.SelectedItem = "Arial";
                comboBoxTamanho.SelectedItem = "12";
                comboBoxEstilo.SelectedItem = "Normal";

            }

            private void Formatar()
            {
                int tamanho = int.Parse(comboBoxTamanho.Text);
                FontStyle estilo = new FontStyle();
                switch(comboBoxEstilo.SelectedItem.ToString())
                {
                    case "Normal":
                        estilo = FontStyle.Regular;
                        break;

                    case "Negrito":
                        estilo = FontStyle.Bold;
                        break;

                    case "Itálico":
                        estilo = FontStyle.Italic;
                        break;

                    case "Sublinhado":
                        estilo = FontStyle.Underline;
                        break;
                }

              richTextBoxTexto.SelectionFont = new Font(comboBoxTipo.SelectedItem.ToString(), tamanho, estilo);
            }
        }
    }

当我从ComboBox更改值时,Richbox的文本不会更改。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您需要在comboBoxEstilo上使用eventhandler。通过这种方式,您可以捕获更改Combobox中的值时发生的事件。

要添加eventhandler,请将其添加到例如load:

private void Form1_Load(object sender, EventArgs e)
{
   ...
   this.comboBoxEstilo.SelectedIndexChanged += 
        new System.EventHandler(comboBoxEstilo_SelectedIndexChanged);
   ...
}

并添加Eventhandler:

    private void comboBoxEstilo_SelectedIndexChanged(object sender, EventArgs e)
    {
        Formatar();
    }