我们正在编写自定义UserControl(而不是无形控件),我们需要根据消费者在XAML中控制的属性执行一些初始化.
现在在大多数情况下,您将使用Initialized事件(或OnInitialized覆盖),因为在触发时,已应用所有XAML集属性,但在UserControl的情况下,情况并非如此.触发Initialized事件时,所有属性仍处于默认值.
我没有注意到其他控件,只是UserControls,不同之处在于它们在构造函数中调用InitializeComponent(),所以作为测试,我评论说该行并运行代码,果然,这次是在Initialized期间事件,属性进行设置.
以下是一些代码和测试结果,证明了这一点......
在构造函数中调用InitializeComponent的结果:(
注意:值仍未设置)
TestValue (Pre-OnInitialized): Original Value
TestValue (Initialized Event): Original Value
TestValue (Post-OnInitialized): Original Value
Run Code Online (Sandbox Code Playgroud)
InitializeComponent完全注释掉的结果:(
注意:在设置值时,控件未加载,因为它需要InitializeComponent)
TestValue (Pre-OnInitialized): New Value!
TestValue (Initialized Event): New Value!
TestValue (Post-OnInitialized): New Value! // Event *was* called and the property has been changed
Run Code Online (Sandbox Code Playgroud)
所有这些说,我可以使用什么来初始化我的控件基于XAML中的用户设置属性?(注意:加载已经太晚了,因为到那时控件应该已经初始化了.)
XAML片段
<local:TestControl TestValue="New Value!" />
Run Code Online (Sandbox Code Playgroud)
TestControl.cs
public partial class TestControl : UserControl
{
public TestControl()
{
this.Initialized += TestControl_Initialized;
InitializeComponent();
}
protected override void OnInitialized(EventArgs e)
{
Console.WriteLine("TestValue (Pre-OnInitialized): " + TestValue);
base.OnInitialized(e); …Run Code Online (Sandbox Code Playgroud)