gpt4 book ai didi

.net - WPF UserControl 的初始化事件未触发

转载 作者:行者123 更新时间:2023-12-03 18:04:54 27 4
gpt4 key购买 nike

我有一个非常简单的 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 doc

This event will be raised whenever theEndInit or OnVisualParentChangedmethods are called. Calls to eithermethod could have come fromapplication code, or through theExtensible Application Markup Language(XAML) processor behavior when a XAMLpage is processed.


我可以在这里重现您的问题。我建议使用 Loaded而是在控件布局和呈现后触发的事件。如果您真的需要 Initialized事件,听从这个 MSDN Forum thread的建议并在 UserControl 的构造函数中附加一个事件处理程序调用前 InitializeComponent()像这样:
public UserControl1()
{
this.Initialized += delegate
{
MessageBox.Show("Hello!");
};
InitializeComponent();
}
更详细的解释 Loaded对比 Initialized ,见 this blog posting .

关于.net - WPF UserControl 的初始化事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/190749/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com