Álvaro García
Álvaro García

Reputation: 19356

How to host a winform chart control into a WPF view?

I am trying use the charts of winforms, that has many chart controls but I can't to use this controls in a wpf view. I have this axml code:

<Window x:Class="WPFCharts.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:charts="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
        Title="MainWindow" Height="440.789" Width="863.158" Loaded="Window_Loaded">
    <Grid Name="grdgraficos">



        <TabControl VerticalAlignment="Stretch" Margin="0,0,0,0" HorizontalAlignment="Stretch">
            <TabItem Header="WPF Controls">
                <Grid Background="#FFE5E5E5">
                    <charts:Chart  Name="pieChart" Title="Pie Series Demo" Margin="0,0,0,0">
                        <charts:PieSeries DependentValuePath="y" 
                IndependentValuePath="campo" ItemsSource="{Binding}" 
                IsSelectionEnabled="True" />
                    </charts:Chart>
                </Grid>
            </TabItem>
            <TabItem Header="WinForms Controls">
                <Grid Background="#FFE5E5E5">
                    <WindowsFormsHost Name="wfhGraficoWinForm" HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Bottom" />
                </Grid>
            </TabItem>
        </TabControl>

    </Grid>
</Window>

And I have this code-behind. By the moment it's a first solution, in the future I will use the MVVM pattern:

private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.DataVisualization.Charting.Chart miGraficoWF = new System.Windows.Forms.DataVisualization.Charting.Chart();
            System.Windows.Forms.DataVisualization.Charting.Series miSerieWF = new System.Windows.Forms.DataVisualization.Charting.Series();
            miSerieWF.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Bar;
            miGraficoWF.Series.Clear();
            miGraficoWF.Series.Add(miSerieWF);
            miSerieWF.Points.AddY(2);
            miSerieWF.Points.AddY(5);
            miSerieWF.Points.AddY(1);

            wfhGraficoWinForm.Child = miGraficoWF;
        }

However the control is not show.

If I create a winform poject and use the same code the chart is shown, so I think that the code that create the chart is correct and the problem is that I don't know how to show the winform control in a wpf view.

Thanks.

Upvotes: 3

Views: 2833

Answers (1)

Pragmateek
Pragmateek

Reputation: 13374

The issue is not at the WPF/WinForms interop layer but in the WinForms.

You must add a ChartArea:

miGraficoWF.ChartAreas.Add("Default");

Upvotes: 3

Related Questions