现在,在大多数情况下,您会使用Initialized事件(或OnInitialized重载),因为此时所有通过XAML设置的属性都已应用,但在UserControl的情况下,情况并非如此。当Initialized事件触发时,所有属性仍处于默认值。
我没有注意到其他控件,只有UserControls不同,它们在构造函数中调用InitializeComponent(),所以我注释了那行代码并运行了代码,果然,在Initialized事件期间,属性被设置了。
以下是一些代码和测试结果说明这一点...
在构造函数中调用InitializeComponent的结果:
(注意:值仍未设置)
TestValue (Pre-OnInitialized): Original Value
TestValue (Initialized Event): Original Value
TestValue (Post-OnInitialized): Original Value
将InitializeComponent完全注释掉后的结果:
(注意:虽然值已经设置,但控件没有加载,因为它需要InitializeComponent)
TestValue (Pre-OnInitialized): New Value!
TestValue (Initialized Event): New Value!
TestValue (Post-OnInitialized): New Value! // Event *was* called
并且属性已经被改变
所有这些都说了,我可以使用什么来基于用户在XAML中设置的属性初始化我的控件?(注意:Loaded太晚了,因为控件应该已经被初始化了。)
XAML片段
<local:TestControl TestValue="New Value!" />
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);
Console.WriteLine("TestValue (Post-OnInitialized): " + TestValue);
}
void TestControl_Initialized(object sender, EventArgs e) {
Console.WriteLine("TestValue (Initialized Event): " + TestValue);
}
public static readonly DependencyProperty TestValueProperty = DependencyProperty.Register(
nameof(TestValue),
typeof(string),
typeof(TestControl),
new UIPropertyMetadata("Original Value"));
public string TestValue {
get => (string)GetValue(TestValueProperty);
set => SetValue(TestValueProperty, value);
}
}