Search code examples
.netwpf.net-3.5

Initialized event of WPF UserControl not firing


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!


Solution

  • 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.