在c#中更改字体样式

您好,我想通过选择dorpdownlist提供的选项来更改aspx页面中标签的字体样式。 这些方法都不起作用。 我知道我可能走在正确的道路上,但似乎无法做到正确。 请赐教。 谢谢在我的代码背后:

public void button1_Click(object sender, EventArgs e) { var select= drop1.SelectedItem.Value; if(select == "Times New Roman") { // I tried doing all of these: label1.Font= new Font("Times New Roman", label1.Font.Size); //or label1.Font.Name ="Times New Roman"; //or Label new1 = new Label("Times New Roman"); Label1.Font= new1; } } 

你最好使用jquery

将事件处理程序绑定到选择下拉列表上的onchange事件,并根据值更改css类。 这有一个好处 – 不是服务器端,避免在服务器上点击b – 更容易c – 清洁

编辑:这样的事情可以改编

jQuery onchange / onfocus选择框来显示图像?

你需要这样做吗? 无论如何,这不是一个“好的”解决方案。 分配一个css类要好得多。 我之前没有见过这种方式……但我会说它来自WinForms。

请改用CssClass:

 label1.CssClass = "SomeClass"; 

并在样式表中定义样式:

 .SomeClass { font-family: "Times New Roman"; font-size: 1.2em; } 

这是我的代码

 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication2 { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { Label1.Font.Name = "Verdana"; } } 

}

并且它正在工作,我只需要你确保在运行应用程序之前为你的标签设置一个fontname,因为当你把它放在你的页面时,fontname是空的( 如果你最初没有设置字体名它就不起作用 )您需要设置它,然后使用上面的代码。打开属性窗口,单击标签,然后单击字体,然后选择字体名称的名称 打开属性窗口单击标签,然后单击字体,然后选择字体名称的名称

在Web上,我们不创建new Font这适用于桌面编程,而新的Font是在服务器上而不是在客户端上创建的。

Label包含.Font但不设置新字体,而是实际创建新的内联样式,对象是FontInfo (不是Font)。

从MSDN FontInfo这里是一个例子:

 // Note that myLabel.Font is a FontInfo object. myLabel.Font.Bold = true; myLabel.Font.Italic = false; myLabel.Font.Name = "verdana"; myLabel.Font.Overline = false; myLabel.Font.Size = 10; myLabel.Font.Strikeout = false; myLabel.Font.Underline = true; // Write information on the FontInfo object to the myLabel label. myLabel.Text = myLabel.Font.ToString(); 

最终渲染包含内联样式,以将此属性赋予span或div内的文本。 当然更好的是给全局css类,但有时你需要干扰内联样式。