Frage

I have a parameterised constructor in My Application. I want to add controls dynamically to my silverlight Child Control Page. But it gives NullReferenceException. I can't find out why it returns null.Can any help me with this situation?

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

Thanks.

War es hilfreich?

Lösung

I guess objStack is a stackpanel declared in your XAML? Be aware that the UI component of your xaml are build by the call to InitializeComponent.

Thus objStack will not exist until you call InitializeCOmponent() in your constructor.

Also, you should know that the call to InitializeComponent is asynchronous, so you code should look like something like that:

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

Hope it helps.

Andere Tipps

As per my research i got that, why it raises an exception: Because there is no

InitializeComponent() in My Constructor and am not calling parent constructor.

That is the reason it raises Exception.

Just Add InitializeComponent() to the code, simple

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top