Search code examples
c#xamlmahapps.metrooxyplotcaliburn

Bind Oxyplot to MahApps AccentColorBrush programmatically


I'm working with MahApps and trying to get its accent color to automatically apply to an OxyPlot chart. I'm using Caliburn and setting up my LineSeries programmatically in my viewmodel as Such:

_bubbleSeries = new LineSeries
{
    StrokeThickness = 2,
    Color = {Binding AccentColorBrush} // <-- This line here would be nice
    CanTrackerInterpolatePoints = false,
    Title = "Bubbles",
    Smooth = true,
};

Binding to the AccentColorBrush would be easy in XAML, but OxyPlot won't allow me to set up a LineSeries in XAML so any advice on how to do this programmatically in my ViewModel would be greatly appreciated.


Solution

  • You can just set the AccentColor via code behind

    _bubbleSeries.SetResourceReference(ColorProperty, "AccentColor");
    

    the benifit is, that this is DynamicResource, so it just changes if you change the accent or theme.

    EDIT

    After I learned that LineSeries isn't a FrameworkElement I can give another possible solution.

    The ThemeManager has an event to react on the theme change.

    ThemeManager.IsThemeChanged += ThemeManager_IsThemeChanged;
    
    void ThemeManager_IsThemeChanged(object sender, OnThemeChangedEventArgs e)
    {
        // handle theme change
    }
    

    With these event arguments.

    public static event EventHandler<OnThemeChangedEventArgs> IsThemeChanged;
    
    public class OnThemeChangedEventArgs : EventArgs
    {
        public AppTheme AppTheme { get; set; }
    
        public Accent Accent { get; set; }
    }
    

    So you can set the color like this

    // this = maybe your window
    var accentColor = ThemeManager.GetResourceFromAppStyle(this, "AccentColor")
    // or
    var accentColor = ThemeManager.GetResourceFromAppStyle(Application.Current.MainWindow, "AccentColor")
    
    // initial
    _bubbleSeries = new LineSeries
    {
        StrokeThickness = 2,
        Color = accentColor,
        CanTrackerInterpolatePoints = false,
        Title = "Bubbles",
        Smooth = true,
    };
    

    And now after theme change

    void ThemeManager_IsThemeChanged(object sender, OnThemeChangedEventArgs e)
    {
        // handle theme change
        _bubbleSeries.Color  = e.Accent.Resources["AccentColor"];
    }
    

    Hope this helps now!