2013-02-11 47 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()的代碼,簡單