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!
The MSDN doc says
I can reproduce your problem here. I would recommend using the
Loadedevent instead, which is fired after the control is laid out and rendered. If you really need theInitializedevent, follow the advice of this MSDN Forum thread and attach a event handler in the constructor of theUserControlbefore callingInitializeComponent()like this:For a more detailed explanation of
Loadedvs.Initialized, see this blog posting.