NameScope与WPF中Win Form Form的FindName()问题

时间:2014-05-03 21:29:52

标签: c# wpf xaml charts

我正在尝试在WPF应用程序中使用Windows表单图表(System.Web.UI.DataVisualization.Charting)。我关注this SO article,到目前为止它非常有帮助。我可以创建一个新的WPF应用程序,逐字复制/粘贴代码,它按预期工作。

MainWindow.xaml.cs

namespace MetroApplication3
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        Dictionary<int, double> value;

        public MainWindow()
        {
            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            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="MetroApplication3.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="My App" Name="mainWindow" Height="695.522" Width="1019.403" Foreground="White" Loaded="Window_Loaded" Icon="favicon.ico">
    <Grid>
        <TabControl Name="tabControl1">
            <TabItem Name="tab1" Header="Tab 1">
                ...
            </TabItem>
            <TabItem Name="tab2" Header="Tab 2">
                <Grid>
                    <StackPanel Name="chartPanel">
                        <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>
                </Grid>
            </TabItem>
        </TabControl>
    </Grid>
</Window>

项目构建没有问题,但是当我启动程序时,我得到了#34; TargetInvocationException未处理&#34;。 System.Reflection.TargetInvocationException中发生了PresentationFramework.dll类型的未处理异常。

在研究了这个问题之后,我很确定我已经确定问题出在窗口的NameScope上。我想这是因为我Chart嵌套在TabItem内。我在MainWindow.xaml.cs中测试了Chart chart = this.FindName("MyWinformChart") as Chart;的结果,chart为空。

我需要采取哪些步骤来解决这个名称问题?如果控件是嵌套的,我可以不使用this.FindName("MyWinformChart")吗?我该如何修改声明?

0 个答案:

没有答案