代码:
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();
}
上一篇:如何将值从窗口传递到 WPF 中的用户控件控件、如何将、窗口、用户
下一篇:设置Window.FEATURE_CUSTOM_TITLE创建AndroidRuntimeExceptionWindow、FEATURE_CUSTOM_TITLE、AndroidRuntimeExce