Sharing An Axis
This sample uses C# 13 preview features such as partial properties, it also uses features from the CommunityToolkit.Mvvm package, you can learn more about it here.
View model
using System;
namespace ViewModelsSamples.Axes.Shared;
public class ViewModel
{
public int[] Values1 { get; set; } =
Fetch(100);
public int[] Values2 { get; set; } =
Fetch(50);
public Func<double, string> Labeler { get; set; } =
value => value.ToString("N2");
// when the data in both charts have different ranges, we can set an initial
// limit so both axes are aligned, also see the DrawMargin property, it also helps
// to align the axes
public int Max => Math.Max(Values1.Length, Values2.Length);
private static int[] Fetch(int length = 50)
{
var values = new int[length];
var r = new Random();
var t = 0;
for (var i = 0; i < length; i++)
{
t += r.Next(-90, 100);
values[i] = t;
}
return values;
}
}
XAML
<UserControl
x:Class="WPFSample.Axes.Shared.View"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:lvc="clr-namespace:LiveChartsCore.SkiaSharpView.WPF;assembly=LiveChartsCore.SkiaSharpView.WPF"
xmlns:vms="clr-namespace:ViewModelsSamples.Axes.Shared;assembly=ViewModelsSamples">
<UserControl.DataContext>
<vms:ViewModel/>
</UserControl.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--
We define a SharedAxesPair, it contains a pair of axes, one for each chart.
The SharedAxesPair class will take care of keeping the axes in sync as the user
zooms and pans the charts.
-->
<Grid.Resources>
<lvc:SharedAxesPair x:Key="SharedAxes">
<lvc:SharedAxesPair.First>
<lvc:XamlAxis
CrosshairLabelsBackground="#FF4500"
CrosshairLabelsPaint="#FFF"
CrosshairPaint="#40FF4500"
Labeler="{Binding Labeler}"
MaxLimit="{Binding Max}"/>
</lvc:SharedAxesPair.First>
<lvc:SharedAxesPair.Second>
<lvc:XamlAxis
CrosshairPaint="#40FF4500"
MaxLimit="{Binding Max}"/>
</lvc:SharedAxesPair.Second>
</lvc:SharedAxesPair>
</Grid.Resources>
<!--
We force the left margin in the "DrawMargin" to 70 in both charts, this to align the
axes no matter the size of the labels on each axis.
-->
<lvc:CartesianChart
Grid.Row="0"
XAxes="{lvc:FromSharedAxes AxesPair={StaticResource SharedAxes}, Element=First}"
DrawMargin="70,Auto,Auto,Auto"
ZoomMode="X">
<lvc:CartesianChart.Series>
<lvc:SeriesCollection>
<lvc:XamlLineSeries Values="{Binding Values1}"/>
</lvc:SeriesCollection>
</lvc:CartesianChart.Series>
</lvc:CartesianChart>
<lvc:CartesianChart
Grid.Row="1"
XAxes="{lvc:FromSharedAxes AxesPair={StaticResource SharedAxes}, Element=Second}"
DrawMargin="70,Auto,Auto,Auto"
ZoomMode="X">
<lvc:CartesianChart.Series>
<lvc:SeriesCollection>
<lvc:XamlColumnSeries Values="{Binding Values2}"/>
</lvc:SeriesCollection>
</lvc:CartesianChart.Series>
</lvc:CartesianChart>
</Grid>
</UserControl>