WPF: add a page with functionality to the window at runtime, like XAML

I created a WPF application in which I dynamically create XAML elements using C # code, and then add them to the root "container" grid.

What I'm trying to do is take advantage of Blend and create some XAML pages that have their own set of code behind the logic, Storyboards, etc.

I want to load this XAML at runtime, but for some reason my approach does not work, and I do not understand why.

This is what I did before. In my root window, I create a new MyModule and add it to my contentRoot.

 myModule = new MyModule();
 contentRoot.Children.Add(myModule );

(The approach that works) The MyModule class extends Canvas and consists of a .XAML file and .CS code behind the file. XAML is just the root canvas, and .CS has all the logic for creating elements and adding them to the root canvas.

When I use the same approach in which MyModule now continues, the page does not appear. XAML now has a lot of content, including Canvas.Resources Canvas.Triggers and many other elements.

How can I load pre-created XAML content from a class, including the code behind the logic at runtime?

+3
source share
3 answers

Page and canvas are two different types of components in XAML.

- , Canvas - Container, , x, y. "", .

Blend , Canvas "Canvas.SetLeft" .., , , .

"", "" , .

MSDN,

. . , , Grid, StackPanel DockPanel, .

"" .

, MyModule , , MyModulePage, .

<MyModulePage>
    <MyModule/> <!-- that is your canvas generated in blend -->
</MyModulePage>
+4

, -, .

MyModule :

<Page x:Class="WpfApplication3.MyModule"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">
</Page>


public partial class MyModule : Page
{
    public MyModule()
    {
        InitializeComponent();
        this.Content = new TextBlock(new Run("WOW!"));
    }
}

MyModuleStandalone.xaml:

<local:MyModule xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:local="clr-namespace:WpfApplication3;assembly=WpfApplication3"                
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
</local:MyModule>

. c, "WOW!".

FileStream xamlFile = new FileStream("MyModuleStandalone.xaml", FileMode.Open, FileAccess.Read);
MyModule c= (MyModule)XamlReader.Load(xamlFile);
this.Content = c;

var c MyModule, . , ?

x: Class XAML, , XAML , ​​- . XamlReader .

, XAML , . xaml.

+3
  FileStream xamlFile = new FileStream("Resources/News/NewsModuleCanvas.xaml", FileMode.Open, FileAccess.Read);
  Canvas newsCanvas = (Canvas)XamlReader.Load(xamlFile);
  contentRoot.Children.Add(newsCanvas);

Used to load XAML, however it still does not give me the opportunity to add the code that underlies the logic as well.

0
source

Source: https://habr.com/ru/post/1714913/


All Articles