daniel
daniel

Reputation: 35703

Fire Event from dynamically loaded XAML

I load an XAML file (page) on runtime in my WPF application:

<Frame x:Name="xamlNode"></Frame>

code behind:

FileStream s = new FileStream("Page1.xaml", FileMode.Open);  
xamlNode.Source = new Uri("Page1.xaml", UriKind.RelativeOrAbsolute);
xamlNode.NavigationUIVisibility = NavigationUIVisibility.Hidden;
s.Close();

First thing I find strange is that the Code is executed I run on Page1.xaml.cs. shouldn't be this XAML file be without any business logic? Neverteheless this is what I need.

But how can I raise an event in my parent WPF application from the Page1.xaml.cs e.g. on a button press?

The origin of my problem is: I need a user to design simple "pages" in VS and then load on runtime. But I need an event when user finished something on that pages.

Upvotes: 0

Views: 287

Answers (1)

Alex.Wei
Alex.Wei

Reputation: 1883

Frist, for your problem, you can handle any routed event raised by any visual descendants by using UIElement.AddHandler method. Assume you have registered a handler for Frame.Loaded event.

private void Frame_Loaded(object sender, RoutedEventArgs e)
{
    ((UIElement)sender).AddHandler(Buttion.ClickEvent, (RoutedEventHandler)((s, e1) =>
    {
        Button btn = (Button)e1.OriginalSource;
        if (btn.Name == "same kind of id")
        {
            // handle the event.
        }
    }));
}

And for the Page1.xaml code executed problem, if you compliled the xaml file, the code will executed because you specify the page as the Source of the Frame. I have to point out that the FileStream have nothing to do with loading Page1.xaml. In the other hand, if you use a loose xaml as the source of the frame, any code should not allowed for xaml. So please check your build action for Page1.xaml.

Upvotes: 1

Related Questions