例外使用动态添加控件到silverlight childwindow?

时间:2013-02-11 11:59:10

标签: silverlight silverlight-4.0 silverlight-3.0

我在My Application中有一个参数化构造函数。我想动态添加控件到我的Silverlight Child Control Page。但它给出了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;
 } 

感谢。

2 个答案:

答案 0 :(得分:0)

我猜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); 
}

希望它有所帮助。

答案 1 :(得分:0)

根据我的研究,我得到了,为什么它会引发异常:因为没有

My Constructor中的InitializeComponent()并没有调用父构造函数。

这就是它引发异常的原因。

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