Dot-Net
WPF UserControl 的初始化事件未觸發
我有一個非常簡單的 WPF UserControl,如下所示:
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); } } }然後我在標準 WPF 視窗的 XAML 中使用它,如下所示:
<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>上面的 WPF 視窗後面的程式碼如下所示:
private void uControl1_Initialized(object sender, EventArgs e) { MessageBox.Show("Hello!"); }不幸的是 Initialized 事件從未被觸發。誰能告訴我為什麼?
非常感謝!
MSDN文件說
每當呼叫 EndInit 或 OnVisualParentChanged 方法時都會引發此事件。對任一方法的呼叫可能來自應用程式碼,或者在處理 XAML 頁面時通過可擴展應用程序標記語言 (XAML) 處理器行為。
我可以在這裡重現您的問題。我建議改用
Loaded事件,它在控制項佈局和呈現後觸發。如果您確實需要該Initialized事件,請遵循此MSDN 論壇執行緒UserControl的建議,並在呼叫之前的建構子中附加一個事件處理程序,InitializeComponent()如下所示:public UserControl1() { this.Initialized += delegate { MessageBox.Show("Hello!"); }; InitializeComponent(); }有關
Loadedvs.的更詳細說明Initialized,請參閱此部落格文章。