2009-11-03 2 views
1

Dans le contrôle System.Web.UI.DataVisualization.Charting.Chart, une police peut être définie en faisant référence à Font par son nom de famille. Comment puis-je faire quelque chose de similaire dans le code?Comment obtenir une police à partir d'une chaîne?

<asp:Chart runat="server"> 
    <legends> 
     <asp:Legend Font="Microsoft Sans Serif, 8.25pt, style=Bold"/> 
    </legends> 
</asp:Chart> 

Comment faire quelque chose de similaire dans le codebehind?

chart.Legends[0].Font = Font.???("Microsoft Sans Serif, 8.25pt, style=Bold") 

Répondre

5

Utilisez one of the constructors la classe System.Drawing.Font:

chart.Legends[0].Font = new Font("Microsoft Sans Serif", 
           8.25, 
           FontStyle.Bold); 

Assurez-vous d'inclure System.Drawing pour obtenir un accès facile à tous les articles connexes (FontFamily, FontStyle, etc.).

+0

+1 Mais je préfère: nouvelle police (nouvelle FontFamily ("Comic Sans MS"), 8,25, FontStyle.BOLD | FontStyle.BlinkText); –

+0

@Chris Ballance: -100 millions pour BlinkText. +1 pour Comic Sans. –

+0

Cela fonctionnera, mais il ne répond pas exactement à la question, j'aurais pensé peut-être qu'il y avait quelque chose dans le cadre qui va consommer toute la chaîne et l'analyser. :) – Dave

1

Utilisez la surcharge suivante du constructeur System.Drawing.Font:

chart.Legends[0].Font = new Font("Microsoft Sans Serif", 8.25, FontStyle.Bold); 
2

Vous pourriez être en mesure de l'analyser, en supposant qu'il est toujours venu en sous cette forme:

string[] fontStrings = "Microsoft Sans Serif, 8.25pt, style=Bold".Split(','); 
fontStrings[1] = fontStrings[1].Replace("pt", ""); 
fontStrings[2] = fontStrings[2].Replace("style=", ""); 
var font = new System.Drawing.Font(
    fontStrings[0], 
    float.Parse(fontStrings[1]), 
    ((FontStyle)Enum.Parse(typeof(FontStyle), fontStrings[2])) 
); 

EDIT: Ah, Je l'ai fait à la dure. Si ce n'est pas dynamique, les autres réponses sont nettement plus agréables que mon string-munging. :)

Questions connexes