向silverlight childwindow动态添加控件时出现异常?

向silverlight childwindow动态添加控件时出现异常?,silverlight,silverlight-4.0,silverlight-3.0,Silverlight,Silverlight 4.0,Silverlight 3.0,我的应用程序中有一个参数化构造函数。我想将控件动态添加到silverlight子控件页。但它给出了NullReferenceException。 我不知道它为什么返回null。有什么能帮我解决这个问题吗 public PDFExport(FrameworkElement graphTile1, FrameworkElement graphTile2,FrameworkElement graphTile3) { Button btnGraph1 = new Button(); strin

我的应用程序中有一个参数化构造函数。我想将控件动态添加到silverlight子控件页。但它给出了
NullReferenceException
。 我不知道它为什么返回null。有什么能帮我解决这个问题吗

public PDFExport(FrameworkElement graphTile1, FrameworkElement graphTile2,FrameworkElement graphTile3)
{

  Button btnGraph1 = new Button();
  string Name = graphTile1.Name;
  btnGraph1.Content = Name;
  btnGraph1.Width = Name.Length;
  btnGraph1.Height = 25;
  btnGraph1.Click += new RoutedEventHandler(btnGraph1_Click);
  objStack.Children.Add(btnGraph1);
  LayoutRoot.Children.Add(objStack); // Here am getting null Reference Exception


  _graphTile1 = graphTile1;
  _graphTile2 = graphTile2;
  _graphTile3 = graphTile3;
 } 

谢谢。

我想objStack是在XAML中声明的stackpanel? 请注意,xaml的UI组件是通过调用InitializeComponent构建的

因此,除非在构造函数中调用InitializeCOmponent(),否则objStack将不存在

另外,您应该知道对InitializeComponent的调用是异步的,因此您的代码应该如下所示:

private readonly FrameworkElement _graphTile1;
private readonly FrameworkElement _graphTile2;
private readonly FrameworkElement _graphTile3;

public PDFExport(FrameworkElement graphTile1, FrameworkElement graphTile2, FrameworkElement graphTile3)
{
    _graphTile1 = graphTile1;
    _graphTile2 = graphTile2;
    _graphTile3 = graphTile3;
}

private void PDFExport_OnLoaded(object sender, RoutedEventArgs e)
{
    Button btnGraph1 = new Button();
    string Name = _graphTile1.Name;
    btnGraph1.Content = Name;
    btnGraph1.Width = Name.Length;
    btnGraph1.Height = 25;
    btnGraph1.Click += new RoutedEventHandler(btnGraph1_Click);
    objStack.Children.Add(btnGraph1);
    LayoutRoot.Children.Add(objStack); 
}

希望它能有所帮助。

根据我的研究,我得到了一个例外:因为没有

InitializeComponent()在我的构造函数中,我没有调用父构造函数

这就是它引发异常的原因


只需将InitializeComponent()添加到代码中,简单的

堆栈跟踪将有所帮助……您好,Quarzy,是的,您的权利。