I had some difficulties with bindng data to custom controll's value made by someone else so i used "Loaded" event to assign control's value during, but i've noticed that this event is fired 开发者_如何转开发up twice.
How can i find out what's firing that event? (VS2008) Or mayby any solution would be expected :)
More than twice, your Loaded event will fire (basically) every time your control becomes visible. For example, a control on a tab control will fire its Loaded event every time you switch to its tab.
Here's a simple solution:
bool m_Loaded = false;
void Loaded(object sender, RoutedEventArgs args)
{
bool tmpLoaded = m_Loaded;
m_Loaded = true;
if (tmpLoaded ) return;
// your code here...
}
Good luck//Jerry
Jerry answer is the common turnaround to the problem of the Loaded event fired every time the control becomes visible.
But I prefer a solution without the continous evaluation of cumbersome flags: just subtract the handler from de event the first time it is fired.
Also, in this way you have the posibility to attach another handler to execute code when the control becomes visible after the first time.
public UserControl1()
{
InitializeComponent();
Loaded += new RoutedEventHandler(UserControl1FirstTime_Loaded);
}
void UserControl1FirstTime_Loaded(object sender, RoutedEventArgs e)
{
Loaded -= UserControl1FirstTime_Loaded; //This handler not called again
...................
//Add next line if you want code to be executed when de control becomes visible
//after first time.
Loaded +=UserControl1AfterFirstTimes_Loaded;
}
void UserControl1AfterFirstTime_Loaded(object sender, RoutedEventArgs e)
{
//Code to be executed when the control becomes visible after first time
....
}
As explained in this blog, the Loaded event is fired when ever a control is about to be rendered (i.e. added to the visual tree).
There are several controls that would cause your control to be loaded/unloaded multiple times. For example, the native WPF TabControl only renders the content of the selected tab. So when you select a new tab, the content of the previously selected tab is unloaded. If you click back to the previously selected tab, then it's content is reloaded.
精彩评论