~/cartesianChart/legends.md
Legends
A legend is a visual element that displays a list with the name, stroke and fills of the series in a chart:
You can place a legend at Top
, Bottom
, Left
, Right
or Hidden
positions, notice the Hidden
position will
disable legends in a chart, default value is Hidden
.
<lvc:CartesianChart
Series="{Binding Series}"
LegendPosition="Top"><!-- mark -->
</lvc:CartesianChart>
<lvc:CartesianChart
Series="{Binding Series}"
LegendPosition="Bottom"><!-- mark -->
</lvc:CartesianChart>
<lvc:CartesianChart
Series="{Binding Series}"
LegendPosition="Left"><!-- mark -->
</lvc:CartesianChart>
<lvc:CartesianChart
Series="{Binding Series}"
LegendPosition="Right"><!-- mark -->
</lvc:CartesianChart>
<lvc:CartesianChart
Series="{Binding Series}"
LegendPosition="Hidden"><!-- mark -->
</lvc:CartesianChart>
Styling legends
A chart exposes many properties to quickly style a legend:
<lvc:CartesianChart
Series="{Binding Series}"
LegendPosition="Left"
LegendFontFamily="Courier New"
LegendFontSize="25"
LegendTextBrush="#f2f4c3"
LegendBackground="#480032">
</lvc:CartesianChart>
The code above would result in the following legend:
Custom template
If you need to customize more, you can also use the create your own template:
<UserControl x:Class="AvaloniaSample.General.TemplatedLegends.View"
xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:lvc="using:LiveChartsCore.SkiaSharpView.Avalonia"
xmlns:vms="using:ViewModelsSamples.General.TemplatedLegends"
xmlns:ctx="using:LiveChartsCore.Kernel">
<UserControl.DataContext>
<vms:ViewModel/>
</UserControl.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<lvc:CartesianChart Series="{Binding Series}" LegendPosition="Right">
<!-- mark -untilCloses lvc:CartesianChart.LegendTemplate -->
<lvc:CartesianChart.LegendTemplate>
<DataTemplate>
<ItemsControl Items="{Binding Series, RelativeSource={RelativeSource AncestorType=lvc:DefaultLegend}}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Padding="7 5" Background="#F5F5DC">
<StackPanel Orientation="Horizontal">
<TextBlock
Text="{Binding Name}"
VerticalAlignment="Center"/>
<lvc:MotionCanvas
Margin="8 0 0 0"
PaintTasks="{Binding CanvasSchedule.PaintSchedules}"
Width="{Binding CanvasSchedule.Width}"
Height="{Binding CanvasSchedule.Height}"
VerticalAlignment="Center"/>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</lvc:CartesianChart.LegendTemplate>
</lvc:CartesianChart>
</Grid>
</UserControl>