Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialized event of WPF UserControl not firing

Tags:

.net

.net-3.5

wpf

I've got a very simple WPF UserControl that looks like this:

namespace MyUserControl
{
  /// <summary>
  /// Interaction logic for UserControl1.xaml
  /// </summary>
  public partial class UserControl1 : UserControl
  {
    public UserControl1()
    {
      InitializeComponent();
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
      Rect rect = new Rect(RenderSize);
      drawingContext.DrawRectangle(Brushes.AliceBlue, new Pen(Brushes.Red, 1), rect);
      base.OnRender(drawingContext);
    }
  }
}

I then use it in the XAML of a standard WPF window like this:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="clr-namespace:MyUserControl;assembly=MyUserControl"
    Title="Window1" Height="351" Width="496">
    <Grid>
    <mc:UserControl1 Margin="0,0,0,0" Name="uControl1" Initialized="uControl1_Initialized"/>
  </Grid>
</Window>

with the code behind of the above WPF Window looks like this:

private void uControl1_Initialized(object sender, EventArgs e)
{
  MessageBox.Show("Hello!");
}

Unfortunately the Initialized event is never fired. Can anybody please tell me why?

Many thanks!

like image 841
Shunyata Kharg Avatar asked Oct 10 '08 10:10

Shunyata Kharg


1 Answers

The MSDN doc says

This event will be raised whenever the EndInit or OnVisualParentChanged methods are called. Calls to either method could have come from application code, or through the Extensible Application Markup Language (XAML) processor behavior when a XAML page is processed.

I can reproduce your problem here. I would recommend using the Loaded event instead, which is fired after the control is laid out and rendered. If you really need the Initialized event, follow the advice of this MSDN Forum thread and attach a event handler in the constructor of the UserControl before calling InitializeComponent() like this:

public UserControl1()
{
    this.Initialized += delegate
    {
        MessageBox.Show("Hello!");
    };
    InitializeComponent();
}

For a more detailed explanation of Loaded vs. Initialized, see this blog posting.

like image 124
David Schmitt Avatar answered Nov 03 '22 22:11

David Schmitt