2013-02-11 46 views
0

我在我的应用程序中有一个参数化的构造函数。我想动态地添加控件到我的Silverlight儿童控制页面。但它给了NullReferenceException。 我找不出为什么它返回null.Can任何帮助我这种情况?异常使用动态添加控件到silverlight childwindow?

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; 
} 

谢谢。

+0

栈跟踪将有助于... – Memoizer 2013-02-11 13:46:07

回答

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

希望它能帮助。

+0

嗨Quarzy,是你的权利。 – Subbu 2013-02-12 07:59:44

0

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

的InitializeComponent()在我的构造,我不叫父类的构造。

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

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