To use the code in your own project, you may copy the code inside the "createChart" method to your project, and change the "viewer" variable to the name of your control.
In this section, we will provide step by step instructions as an example.
- Add a reference to ChartDirector to your WPF project. See Using ChartDirector in Your Own Projects.
- Drag a ChartDirector WPFChartViewer control from the Visual Studio toolbox onto a Window. Set the ID of the control to "wpfChartViewer1".
When you drag a WPFChartViewer control onto a Window, Visual Studio should automatically insert two lines into the XAML of the Window. This should be like the blue lines below:
<Window x:Class="MyProject.MyFirstWPFChart" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:MyProject" mc:Ignorable="d" xmlns:ChartDirector="clr-namespace:ChartDirector;assembly=netchartdir" UseLayoutRounding="True" Title="My First WPF Chart" SizeToContent="WidthAndHeight" ResizeMode="NoResize" > <Grid> <ChartDirector:WPFChartViewer x:Name="WPFChartViewer1" Width="600" Height="400" /> </Grid> </Window>
The first blue line above maps the XAML namespace ChartDirector to the same namespace in the ChartDirector assembly "netchartdir". The second blue line is the WPFChartViewer control.
*** Note ***: The "netchartdir" is for WPF (.NET Framework). For WPF (.NET Core), the assembly should be "ChartDirector.Net.Desktop.Controls".
Note the red lineUseLayoutRounding="True"
. This line is not automatically added by Visual Studio. We suggest you add this line manually to the XAML. This ensures WPF layout the WPFChartViewer at integral device pixel coordinates. Without this line, WPF may layout the WPFChartViewer at fractional device pixel coordinates using anti-alias methods. As ChartDirector has already anti-aliased the chart, this results in double anti-alias, causing the chart to look less sharp.
- In the code-behind, add the following line at the top.
using ChartDirector;
- Add a Window "Loaded" event handler, and add the following code into the event handler.
//The data for the bar chart double[] data = {85, 156, 179.5, 211, 123}; //The labels for the bar chart string[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"}; //Create a XYChart object of size 250 x 250 pixels XYChart c = new XYChart(250, 250); //Set the plotarea at (30, 20) and of size 200 x 200 pixels c.setPlotArea(30, 20, 200, 200); //Add a bar chart layer using the given data c.addBarLayer(data); //Set the x axis labels using the given labels c.xAxis().setLabels(labels); //output the chart WPFChartViewer1.Chart = c; //include tool tip for the chart WPFChartViewer1.ImageMap = c.getHTMLImageMap("clickable", "", "title='{xLabel}: US${value}K'");