0

I have an expander with a loaded event in xaml, and it works well :

<Expander Name="exp" Loaded="expander_Loaded">

But I try in code-behind :

   Expander ex = new Expander();
   ex.Loaded += new RoutedEventHandler(expander_Loaded);

   void expander_Loaded(object sender, RoutedEventArgs e)
   {
        //code
   }

And it doesn't work.

How can i call expander_Loaded when my expander isLoaded?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Shuyuntake
  • 79
  • 3
  • 13

2 Answers2

1

When you use

<Expander Name="exp" Loaded="expander_Loaded">

you insert a new Expander into your XAML, i.e. the display knows about it and works with it.

When you do:

Expander ex = new Expander();
ex.Loaded += new RoutedEventHandler(expander_Loaded);

void expander_Loaded(object sender, RoutedEventArgs e)
{
    //code
}

you create a new Expander object, assign it an event, and then, if it is not used after that line, promptly discard it. Try

<Expander Name="exp">

with

//refers to the declared object
exp.Loaded += new RoutedEventHandler(expander_Loaded);

void expander_Loaded(object sender, RoutedEventArgs e)
{
    //code
}

to see that it will work. Additionally, if you want to create and add controls at runtime, take a look at this question, that explains working with the Children collection

Community
  • 1
  • 1
SWeko
  • 30,434
  • 10
  • 71
  • 106
0

You shouldn't need to hook up the event in code and in markup. Either remove Loaded="expander_Loaded" or remove ex.Loaded += new RoutedEventHandler(expander_Loaded);. It's possible doing it twice is having this unexpected effect.

Echilon
  • 10,064
  • 33
  • 131
  • 217