tags:

views:

56

answers:

0

I'm currently very confused by the differing behavior regarding the FrameworkElement.Loaded event. I've put together a small example application that demonstrates this.

Xaml:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300"
        Loaded="Window_Loaded">
    <Grid>
        <TabControl>
            <TabItem Header="Tab 1" />
            <TabItem Header="Tab 2" >
                <WindowsFormsHost Name="formHost" Loaded="formHost_Loaded" />
            </TabItem>
        </TabControl>
    </Grid>
</Window>

Code:

using System.Windows;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            formHost.Loaded += delegate
            {
                MessageBox.Show("Delegate");
            };
        }

        private void formHost_Loaded(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Markup");
        }
    }
}

As it is, when I run the application I get two immediate MessageBoxes - "Markup" and "Delegate". If, however, I remove Loaded="formHost_Loaded" from the WindowsFormsHost, I get neither on startup. It obviously makes sense why I don't get the "Markup" dialog, but why does this also remove the "Delegate"? I would imagine it has to do with the order in which the events are called (Window versus its children), but I'm having a tough time figuring it out.

Note: You can replace the WindowsFormsHost with other controls, it really shouldn't matter - I was just using it for another few tests.