Search code examples
c#wpfdata-bindingoxyplot

Setting OxyPlot chart title


I am using OxyPlot to show a basic line-Chart under WPF/.net 4.5 and the relevant part of the XAML looks like this:

<oxy:Plot Title="{Binding Title}">
    <oxy:Plot.Series>
        <oxy:LineSeries ItemsSource="{Binding Points}"/>
        <oxy:LineSeries ItemsSource="{Binding Points2}"/>
    </oxy:Plot.Series>
    <oxy:Plot.Axes>
        <oxy:CategoryAxis Position="Bottom" ItemsSource="{Binding Labels}" />
    </oxy:Plot.Axes>
</oxy:Plot>

The code to create the chart is this:

public class MainViewModel
{

    public MainViewModel()
    {
        this.Title = reader.title;
        this.Points = reader.mylist;
        this.Points2 = reader.mylist2;
        this.Labels = reader.labs;          
    }

    public string Title { get; private set; }
    public IList<DataPoint> Points { get; private set; }
    public IList<DataPoint> Points2 { get; private set; }
    public IList<String> Labels { get; private set; }

}

The properties are set and changed on demand in another method basically simply like this:

public static List<DataPoint> mylist = new List<DataPoint>();
public static List<DataPoint> mylist2 = new List<DataPoint>();
public static List<String> labs = new List<String>();
public static string title;

public void setchart()
{

   mylist.Add(new DataPoint(0,5));
   mylist.Add(new DataPoint(1,10));

   mylist2.Add(new DataPoint(0,30));
   mylist2.Add(new DataPoint(1,25));

   labs.Add("date1");
   labs.Add("date2");

  title = "mytitle";

  MainWin.myPlot.InvalidatePlot(true);

}

It works for the lines in the chart (Points, Points2) and the labels on the x-axis (Labels). But the title of the chart just doesn't update - "mytitle" never appears as title of the chart unless I put it like

this.Title = "mytitle";

directly into MainViewModel().

Some people seem to have similar problems (e.g. here) but I would like to know if I'm doing something wrong.


Solution

  • On your MainViewModel contructor, when you assign the reader Lists to the ILists, both will point to the same object, so when you modify one, the other will be modified too.

    String, on the other hand, although is a reference type, it is imutable, so it behaves pretty much like a value type. So when you modify the string in the reader class, you're not modifying the one in the ViewModel.