Search code examples
c#.netwpfchartstoolkit

How do you change the Title Font for a WPF Chart in code?


I have created a WPF chart programmatically and would like to change the Title's Font and color, I can set the chart's width and height but not the title, all the examples that I have found online show you how to do it through XAML. but I need to be able to do it all in code.

        this._chart.Width = this.ChartWidth;
        this._chart.Height = this.ChartHeight;
        this._chart.Background = Brushes.Transparent;
        ....
        this._chart.Title ????

Thank you.


Solution

  • The easiest way is to use the TextBlock control instead of the plain text:

    this._chart.Title = new TextBlock 
    { 
        Text = "My title", 
        FontFamily = new FontFamily("Arial"), 
        Foreground = Brushes.Red 
    };
    

    The same approach can be used with the legend title. By the way you can use any WPF control, not only the text block.

    this._chart.LegendTitle = new TextBlock { Text = "legend", Foreground = Brushes.Red };
    

    If you want to change a style property like PloatAreaStyle, do it so:

    var plotAreaStyle = new Style(typeof(Grid));
    plotAreaStyle.Setters.Add(new Setter(Grid.BackgroundProperty, Brushes.LightBlue));
    
    this._chart.PlotAreaStyle = plotAreaStyle;