在WPF窗口中嵌入WinForms图形

10

我尝试在WPF窗口下使用WindowsFormsHost(已引用System.Windows.Forms和WindowsFormsIntegration)嵌入一个.NET WinForms图表(Stephan Zimmermann的Graph Display),但只能看到表格面板,而没有看到图表。我已经在Windows窗体上运行了演示应用程序并成功显示了图表,但当我将相同的代码转移到WPF窗口时,我发现数据被更新了,但是图表没有显示。

提前感谢大家,

Yaron。


你能发布一下你的WPF代码吗? - micahtan
4个回答

19

您能尝试下面的代码,看看是否可以显示图形,然后从那里开始调试?

MainWindow.xaml.cs

using System.Collections.Generic;
using System.Windows.Forms.DataVisualization.Charting;
using System.Windows;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        Dictionary<int, double> value;
        public MainWindow()
        {
            InitializeComponent();

            value = new Dictionary<int, double>();
            for (int i = 0; i < 10; i++)
                value.Add(i, 10 * i);

            Chart chart = this.FindName("MyWinformChart") as Chart;
            chart.DataSource = value;
            chart.Series["series"].XValueMember = "Key";
            chart.Series["series"].YValueMembers = "Value";
        }
    }
}

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:winformchart="clr-namespace:System.Windows.Forms.DataVisualization.Charting;assembly=System.Windows.Forms.DataVisualization"
    Title="MainWindow" Height="392" Width="525">
    <StackPanel>

        <WindowsFormsHost x:Name="host" Height="300">
            <winformchart:Chart x:Name="MyWinformChart" Dock="Fill">
                <winformchart:Chart.Series>
                    <winformchart:Series Name="series" ChartType="Line"/>
                </winformchart:Chart.Series>
                <winformchart:Chart.ChartAreas>
                    <winformchart:ChartArea/>
                </winformchart:Chart.ChartAreas>
            </winformchart:Chart>
        </WindowsFormsHost>

    </StackPanel>
</Window>
确保你有以下引用:

%ProgramFiles%\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\Profile\Client\WindowsFormsIntegration.dll

%ProgramFiles%\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\Profile\Client\System.Windows.Forms.DataVisualization.dll

%ProgramFiles%\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\Profile\Client\System.Windows.Forms.dll

我在不好意思地抄袭了这个链接之后使它运行起来。 link

我可以对图表系列进行绑定吗? - Daniel Möller

4

虽然这个问题已经超过6年了,但我遇到了类似的问题,当我试图在运行时创建和添加图表对象时。 感谢Bobwah的建议,我能够找到问题并发现只需向Chart对象添加ChartArea即可看到图形:

Chart chart = new Chart();
chart.ChartAreas.Add("MainChartArea"); //this was missing
chart.Series.Add(getSeries());
chart.Dock = System.Windows.Forms.DockStyle.Fill;
host.Child = chart; //'host' is the WPF-WindowsFormsHost control

希望它能帮助到某些人... ;)

1

我在WPF中遇到了同样的问题。幸运的是,我找到了解决方案。

我观察到一旦设置数据源,图表区域和系列就会被重置。对我来说,这看起来像一个bug。

因此,解决方法/解决方案是在添加诸如图表区域和系列之前首先设置数据源。


0
将图形设置为 WindowsFormsHost 对象的子级。

已经尝试过了,但没有帮助。我仍然无法看到图表的更新。 - Yaron Adler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接