WPF UserControl Initialized Event Does Not Trigger

I have a very simple WPF user control 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);
    }
  }
}

Then I use it in the XAML of the standard WPF window as follows:

<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 above in the WPF window looks like this:

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

Unfortunately, an initialized event never fires. Can someone please tell me why?

Many thanks!

+5
source share
1 answer

MSDN document says

, EndInit OnVisualParentChanged . (XAML), XAML .

. Loaded, , . Initialized, MSDN UserControl InitializeComponent() :

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

Loaded vs. Initialized . .

+13

All Articles