1
votes

I am using a chart (DataVisualization.Charting.Chart) and letting the chart decide the font size for the axes labels (IsLabelAutoFit = True for each axis). After the chart is drawn, I want to know the actual font size used. Microsoft documentation says that LabelStyle.Font is for both Get and Set. However, the Get always returns the default font size (8 pts) rather than the actual font size used. How can I get the true font size used by the chart?

Dim OriginalXLabelFont As Font = thisChart.ChartAreas("ChartArea1").AxisX.LabelStyle.Font
Dim OriginalXTitleFont As Font = thisChart.ChartAreas("ChartArea1").AxisX.TitleFont

I expect the OriginalXLabelFont to be the actual font size used by the chart, but it always just the default size. On the other hand, OriginalXTitleFont properly gives me the actual Title font size that was used. However, the title font is fixed, and does not change dynamically when the chart is drawn. How can I get the axis label font size of the as-drawn chart?

1

1 Answers

3
votes

I poked around and found out that the actual font size used by the graph was in a non-public field of the axis call autoLabelFont. To access it I had to use reflection.

    Dim OriginalXLabelFont As Font = GetPrivateFieldValue(thisChart.ChartAreas("ChartArea1").AxisX, "autoLabelFont")

...

Private Function GetPrivateFieldValue(ByVal thisObject As Object, ByVal propName As String) As Object

    If IsNothing(thisObject) Then Return Nothing

    Dim fi As System.Reflection.FieldInfo = thisObject.GetType().GetField(propName, Reflection.BindingFlags.IgnoreCase Or
                   Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)

    If IsNothing(fi) Then Return Nothing

    Return fi.GetValue(thisObject)

End Function