如何在设置属性后仅进行一次 UserControl 初始化 [英] How to make UserControl initialization only once after property is set
问题描述
代码:
public partial class MyControl : UserControl
{
int size = 8;
public int Size
{
get { return size; }
set { size = value; Initialize(); }
}
public MyControl()
{
InitializeComponent();
Initialize();
}
void Initialize()
{
// ...
}
}
XAML:
<local:MyControl"/>
或:
<local:MyControl Size="10"/>
在 XAML 中设置 Size
属性时,会调用两次 Initialize
.如果我从 InitializeComponent
中删除 Initialize
调用,则 Initialize
会从 Size
设置器中调用一次.但是在这种情况下,如果 XAML 中没有设置 Size
,则根本不会调用 Initialize
.
When Size
property is set in XAML, Initialize
is called twice. If I remove Initialize
call from InitializeComponent
, Initialize
is called once from Size
setter. But in this case, if Size
is not set in XAML, Initialize
is not called at all.
有没有办法编写初始化函数,在所有控件属性(如果有)从 XAML 设置之后执行一次?
Is there any way to write initialization function, which is executed once, after all control properties (if any) are set from XAML?
推荐答案
您可以在 Loaded
事件处理程序中调用 Initialize
方法:
You may call the Initialize
method in a Loaded
event handler:
public partial class MyControl : UserControl
{
int size = 8;
public int Size
{
get { return size; }
set { size = value; }
}
public MyControl()
{
InitializeComponent();
Loaded += (o, e) => Initialize();
}
void Initialize()
{
// ...
}
}
为了确保 Initialize()
方法只被调用一次,尽管 Loaded
可能会被多次触发,像这样分离事件处理程序:
In order to make sure the Initialize()
method is called only once, although Loaded
may be fired more than once, detach the event handler like this:
public MyControl()
{
InitializeComponent();
Loaded += MyControlLoaded;
}
private void MyControlLoaded(object sender, RoutedEventArgs e)
{
Loaded -= MyControlLoaded;
Initialize();
}
这篇关于如何在设置属性后仅进行一次 UserControl 初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!