Installation and first chart
At this point you must enable the include prerelease checkbox to find LiveCharts NuGet packages
Before getting started with Uno, ensure you have installed all the prerequisites, for Visual Studio you can get started here, you can find help on how to install the mentioned workloads here.
Open visual studio 2022, select "Create a new project", then select the Uno Platform App
template.
Name your project and solution UnoApp
and select the Default
template and click Create
.
Install from NuGet
You can install LiveChart from NuGet, in the Solution Explorer
right click on the UnoApp
project, then Manage Nuget Packages
,
in the Browse
tab search for LiveChartsCore.SkiaSharpView.Uno.WinUI
(check the include prerelease checkbox), finally click on Install
.
Notice this guide is for Uno.WinUI (probably the recommended Uno flavor if you are starting a new project) if you need the UWP platform you must install LiveChartsCore.SkiaSharpView.Uno, you can find that guide here, notice docs for UWP version might be outdated.
Add a chart to the UI
Let's start by defining a view model for our chart, in the Solution Explorer
find the UnoApp
project and then open the
Presentation/MainPage.xaml.cs
file, and add the next view model class:
using Windows.UI.Xaml.Controls;
using LiveChartsCore; // mark
using LiveChartsCore.SkiaSharpView; // mark
namespace UnoApp;
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
}
public class ViewModel // mark
{ // mark
public ISeries[] Series { get; set; } // mark
= new ISeries[] // mark
{ // mark
new LineSeries<double> // mark
{ // mark
Values = new double[] { 2, 1, 3, 5, 3, 4, 6 }, // mark
Fill = null // mark
} // mark
}; // mark
} // mark
Now let's add the control to the UI, in the Presentation/MainPage.xaml
file, add the namespace for LiveCharts (lvc)
and for the view model we just created (local).
Set the Page.DataContext
to our view model, and finally add the chart and bind the Series
property to our view model.
<!-- mark -skip 4 -take 2 -->
<Page
x:Class="UnoApp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UnoApp.Presentation"
xmlns:lvc="using:LiveChartsCore.SkiaSharpView.WinUI"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.DataContext>
<local:ViewModel /><!-- mark -->
</Page.DataContext>
<lvc:CartesianChart<!-- mark -->
Series="{Binding Series}"><!-- mark -->
</lvc:CartesianChart><!-- mark -->
</Page>
Now run the application, as you probably already know, an Uno Application can run on multiple platforms, you can decide
which platform to run by opening the Platforms folder then right click on the desired platform then on Set as Startup Project
:
Ensure the startup project is Platforms/UnoApp.Mobile
and browse for an Android emulator, if this is your first time
running an emulator with VisualStudio, you need to install it by clicking on the Android Device Manager
and adding a new device.
And that's it, we have LiveCharts2 running on Android!.
Start the project for the rest of the platforms, the chart is ready to run everywhere!.
Configure themes, fonts or mappers (Optional)
Optionally you could configure LiveCharts to add a theme, register a global font, enable right to left
tooltips
or a custom mapper for a type, when you need a non-Latin font you must register a typeface so SkiaShap can render
the text correctly, add the following code when your application starts:
Go to the Solution Explorer
and browse for UnoApp.Shared/App.xaml.cs
file, then edit the it as follows.
using LiveChartsCore; // mark
using LiveChartsCore.SkiaSharpView; // mark
using SkiaSharp; // mark
namespace UnoPlatformSample;
public class App : Application
{
protected Window? MainWindow { get; private set; }
protected IHost? Host { get; private set; }
public record City(string Name, double Population);
protected async override void OnLaunched(LaunchActivatedEventArgs args)
{
LiveCharts.Configure(config => // mark
config // mark
// you can override the theme
// .AddDarkTheme() // mark
// In case you need a non-Latin based font, you must register a typeface for SkiaSharp
//.HasGlobalSKTypeface(SKFontManager.Default.MatchCharacter('汉')) // <- Chinese // mark
//.HasGlobalSKTypeface(SKFontManager.Default.MatchCharacter('あ')) // <- Japanese // mark
//.HasGlobalSKTypeface(SKFontManager.Default.MatchCharacter('헬')) // <- Korean // mark
//.HasGlobalSKTypeface(SKFontManager.Default.MatchCharacter('Ж')) // <- Russian // mark
//.HasGlobalSKTypeface(SKFontManager.Default.MatchCharacter('أ')) // <- Arabic // mark
//.UseRightToLeftSettings() // Enables right to left tooltips // mark
// finally register your own mappers
// you can learn more about mappers at:
// https://livecharts.dev/docs/unowinui/2.0.0-rc1/Overview.Mappers
.HasMap<City>((city, point) => // mark
{ // mark
// here we use the index as X, and the population as Y // mark
point.Coordinate = new(point.Index, city.Population); // mark
}) // mark
// .HasMap<Foo>( .... ) // mark
// .HasMap<Bar>( .... ) // mark
); // mark
var builder = this.CreateBuilder(args)
// Add navigation support for toolkit controls such as TabBar and NavigationView
.UseToolkitNavigation()
.Configure(host => host
#if DEBUG
// Switch to Development environment when running in DEBUG
.UseEnvironment(Environments.Development)
#endif
.UseLogging(configure: (context, logBuilder) =>
{
// Configure log levels for different categories of logging
logBuilder
.SetMinimumLevel(
context.HostingEnvironment.IsDevelopment() ?
LogLevel.Information :
LogLevel.Warning)
// Default filters for core Uno Platform namespaces
.CoreLogLevel(LogLevel.Warning);
// Uno Platform namespace filter groups
// Uncomment individual methods to see more detailed logging
//// Generic Xaml events
//logBuilder.XamlLogLevel(LogLevel.Debug);
//// Layouter specific messages
//logBuilder.XamlLayoutLogLevel(LogLevel.Debug);
//// Storage messages
//logBuilder.StorageLogLevel(LogLevel.Debug);
//// Binding related messages
//logBuilder.XamlBindingLogLevel(LogLevel.Debug);
//// Binder memory references tracking
//logBuilder.BinderMemoryReferenceLogLevel(LogLevel.Debug);
//// RemoteControl and HotReload related
//logBuilder.HotReloadCoreLogLevel(LogLevel.Information);
//// Debug JS interop
//logBuilder.WebAssemblyLogLevel(LogLevel.Debug);
}, enableUnoLogging: true)
.UseConfiguration(configure: configBuilder =>
configBuilder
.EmbeddedSource<App>()
.Section<AppConfig>()
)
// Enable localization (see appsettings.json for supported languages)
.UseLocalization()
// Register Json serializers (ISerializer and ISerializer)
.UseSerialization((context, services) => services
.AddContentSerializer(context)
.AddJsonTypeInfo(WeatherForecastContext.Default.IImmutableListWeatherForecast))
.UseHttp((context, services) => services
// Register HttpClient
#if DEBUG
// DelegatingHandler will be automatically injected into Refit Client
.AddTransient<DelegatingHandler, DebugHttpHandler>()
#endif
.AddSingleton<IWeatherCache, WeatherCache>()
.AddRefitClient<IApiClient>(context))
.ConfigureServices((context, services) =>
{
// TODO: Register your services
//services.AddSingleton<IMyService, MyService>();
})
.UseNavigation(ReactiveViewModelMappings.ViewModelMappings, RegisterRoutes)
);
MainWindow = builder.Window;
Host = await builder.NavigateAsync<Shell>();
}
private static void RegisterRoutes(IViewRegistry views, IRouteRegistry routes)
{
views.Register(
new ViewMap(ViewModel: typeof(ShellModel)),
new ViewMap<MainPage, MainModel>(),
new DataViewMap<SecondPage, SecondModel, Entity>()
);
routes.Register(
new RouteMap("", View: views.FindByViewModel<ShellModel>(),
Nested: new RouteMap[]
{
new RouteMap("Main", View: views.FindByViewModel<MainModel>()),
new RouteMap("Second", View: views.FindByViewModel<SecondModel>()),
}
)
);
}
}