PDA

View Full Version : IMSL C# Charting and WPF



ed
03-18-2008, 02:05 PM
I have fielded several questions recently about the integration with the Windows.Forms based charting components in the IMSL C# Library into a WPF (Windows Presentation Foundation) application. My answer has been "well, it should work, but I'm not sure how". Now that I have Visual Studio 2008 I have been able to confirm that yes, it will work.

There is a walkthrough on MSDN (http://msdn2.microsoft.com/en-us/library/ms751761.aspx) of exactly this. In short, you need to add a reference to the WindowsFormsIntegration assembly, and then add a bit of code. I followed that walkthrough and tweaked it a bit to include a chart in a second WPF grid. I dropped a normal Button in the outer grid just to show that things can indeed work together. The PanelChart object is created when the form is loaded, and a chart is drawn when the button is clicked.

Walking through the steps gets verbose, but the MSDN walkthrough does a pretty good job. So to summarize, here's the code I ended up with:

Window1.xaml:

<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
Loaded="WindowLoaded">
<Grid Height="248" Width="287">
<Button Height="23" Margin="102,0,101,0" Name="button1" VerticalAlignment="Top" Click="button1_Click">Button</Button>
<Grid Margin="0,46,0,0" Name="grid1" />
</Grid>
</Window>

Window1.xaml.cs:

using System;
using System.Windows;
using Imsl.Chart2D;

namespace WpfApplication1
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
PanelChart pChart;

public Window1()
{
InitializeComponent();
}

private void WindowLoaded(object sender, RoutedEventArgs e)
{
// Create interop host control
System.Windows.Forms.Integration.WindowsFormsHost host =
new System.Windows.Forms.Integration.WindowsFormsHost( );

// Create the control
pChart = new PanelChart();

// Assign the panel as the host control's child
host.Child = pChart;

// Add the interop host control to the Grid
this.grid1.Children.Add(host);
}

private void button1_Click(object sender, RoutedEventArgs e)
{
Chart chart = pChart.Chart;
AxisXY axis = new AxisXY(chart);
double[] y = { 3, 5, 7, 9, 8, 2 };
Data data = new Data(axis, y);
pChart.Refresh();
}
}
}


And finally, a little screenshot of the finished program.

ed
03-18-2008, 02:27 PM
And a screenshot running on Vista, where WPF is really at home.